Generate Tests — Comprehensive Test Suite Generator
Generate complete test coverage for any file, component, or module. Covers unit tests, integration tests, edge cases, error handling, and mocking — adapted to whatever testing framework the project uses.
Use when: you want tests generated for a file or component, need to improve test coverage, want edge case coverage, need mocks for external dependencies, or want to bootstrap a test suite for untested code.
When This Skill Is Activated
Follow every step below. Do NOT generate tests without first analyzing the project's testing setup and the target code.
Step 1: Detect the Testing Setup
Before writing any tests, discover the project's testing conventions:
Find the test framework — Check package.json (dependencies/scripts), or config files:
jest.config.* / jest key in package.json → Jest
vitest.config.* → Vitest
cypress.config.* → Cypress
playwright.config.* → Playwright
pytest.ini / pyproject.toml [tool.pytest] → pytest
go.mod → Go testing
Cargo.toml → Rust (#[cfg(test)])
Find existing test files — Search for *.test.*, *.spec.*, test_*.py, *_test.go to understand naming conventions and patterns already in use.
Check for test utilities — Look for shared helpers, factories, custom matchers, or mock setups the project already provides (e.g., test/utils.ts, __mocks__/, conftest.py).
Check the test script — Read the test script in package.json (or equivalent) to understand how tests are run, what flags are used, and what coverage tool is configured.
Match the project's existing conventions exactly. File naming, import style, assertion style, describe/it vs test, etc.
Step 2: Analyze the Target Code
Read the file or component the user wants tested. Identify:
- All exported functions, classes, methods, and components
- Input types and return types (or infer them)
- External dependencies (API calls, database, file system, third-party libs)
- Side effects (mutations, network calls, timers, DOM manipulation)
- Error paths (throw statements, catch blocks, error returns)
- Edge cases (null/undefined inputs, empty arrays, boundary values, large inputs)
- Async behavior (promises, callbacks, streams)
Step 3: Plan the Test Suite
Before writing code, outline what you'll test:
Unit Tests
- Every exported function with representative inputs
- Return values for happy path
- Error handling for invalid inputs
- Boundary values (0, -1, empty string, null, max int, etc.)
- Type coercion edge cases if applicable
Integration Tests (if the code interacts with other modules)
- Component interactions and data flow
- API calls with mocked responses (success + failure)
- Service layer with mocked dependencies
- State management side effects
Edge Cases and Error Handling
- Null, undefined, empty inputs
- Malformed data
- Network failures / timeouts
- Concurrent access / race conditions
- Extremely large inputs
Step 4: Write the Tests
Follow these principles:
Structure
describe("[ModuleName]", () => {
describe("[functionName]", () => {
it("should [expected behavior] when [condition]", () => {
// Arrange
// Act
// Assert
});
});
});
- Descriptive test names — Read like documentation: "should return empty array when input is null"
- AAA pattern — Arrange (setup), Act (execute), Assert (verify). Separate each visually.
- One assertion per concept — Multiple
expect() calls are fine if they assert one logical thing
- Group with
describe — One block per function/method/component behavior
- Setup/teardown — Use
beforeEach/afterEach for test isolation. Clean up subscriptions, timers, mocks.
Mocking Strategy
- Mock external dependencies only — Don't mock the code under test
- Use the project's existing mock patterns (e.g.,
jest.mock(), vi.mock(), unittest.mock)
- Create test data factories for complex objects instead of inline literals
- Mock timers (
jest.useFakeTimers() / vi.useFakeTimers()) for time-dependent code
- Mock dates for deterministic snapshots
- Always restore mocks in
afterEach to prevent test pollution
Async Testing
- Always
await async functions or return the promise
- Test both resolve and reject paths
- Use
waitFor / findBy for async UI updates (React Testing Library)
- Test loading, success, and error states
Framework-Specific Guidance
| Framework |
Component Testing |
Key Patterns |
| React |
React Testing Library |
render(), screen.getByRole(), userEvent, waitFor |
| Vue |
Vue Test Utils |
mount(), shallowMount(), wrapper.find(), trigger() |
| Angular |
TestBed |
TestBed.configureTestingModule(), fixture.detectChanges() |
| Node.js |
Supertest |
request(app).get("/api/...").expect(200) |
| Python |
pytest |
@pytest.fixture, monkeypatch, parametrize |
| Go |
testing |
t.Run(), table-driven tests, t.Parallel() |
Step 5: Verify and Improve
After generating the tests:
- Run the tests — Execute the test suite to make sure they pass
- Check coverage — Identify untested lines or branches
- Add missing cases — Fill gaps in coverage, especially error paths
- Review test quality — Tests should fail when the code breaks, not just when the tests break
Coverage Goals
| Priority |
Coverage Target |
| Critical business logic |
90%+ |
| Utility functions |
85%+ |
| UI components |
80%+ |
| Configuration/glue code |
60%+ |
Focus on branch coverage over line coverage — untested else and catch paths are where bugs hide.
Output Checklist
Before finishing, verify:
1---2name: generate-tests3description: Generate complete test coverage for any file, component, or module. Covers unit tests, integration tests, edge cases, error handling, and mocking — adapted to whatever testing framework the project uses.4---56# Generate Tests — Comprehensive Test Suite Generator78Generate complete test coverage for any file, component, or module. Covers unit tests, integration tests, edge cases, error handling, and mocking — adapted to whatever testing framework the project uses.910**Use when**: you want tests generated for a file or component, need to improve test coverage, want edge case coverage, need mocks for external dependencies, or want to bootstrap a test suite for untested code.1112---1314## When This Skill Is Activated1516Follow every step below. Do NOT generate tests without first analyzing the project's testing setup and the target code.1718---1920## Step 1: Detect the Testing Setup2122Before writing any tests, discover the project's testing conventions:23241. **Find the test framework** — Check `package.json` (dependencies/scripts), or config files:25 - `jest.config.*` / `jest` key in `package.json` → Jest26 - `vitest.config.*` → Vitest27 - `cypress.config.*` → Cypress28 - `playwright.config.*` → Playwright29 - `pytest.ini` / `pyproject.toml` [tool.pytest] → pytest30 - `go.mod` → Go testing31 - `Cargo.toml` → Rust (#[cfg(test)])32332. **Find existing test files** — Search for `*.test.*`, `*.spec.*`, `test_*.py`, `*_test.go` to understand naming conventions and patterns already in use.34353. **Check for test utilities** — Look for shared helpers, factories, custom matchers, or mock setups the project already provides (e.g., `test/utils.ts`, `__mocks__/`, `conftest.py`).36374. **Check the test script** — Read the `test` script in `package.json` (or equivalent) to understand how tests are run, what flags are used, and what coverage tool is configured.3839**Match the project's existing conventions exactly.** File naming, import style, assertion style, describe/it vs test, etc.4041---4243## Step 2: Analyze the Target Code4445Read the file or component the user wants tested. Identify:4647- All exported functions, classes, methods, and components48- Input types and return types (or infer them)49- External dependencies (API calls, database, file system, third-party libs)50- Side effects (mutations, network calls, timers, DOM manipulation)51- Error paths (throw statements, catch blocks, error returns)52- Edge cases (null/undefined inputs, empty arrays, boundary values, large inputs)53- Async behavior (promises, callbacks, streams)5455---5657## Step 3: Plan the Test Suite5859Before writing code, outline what you'll test:6061### Unit Tests62- Every exported function with representative inputs63- Return values for happy path64- Error handling for invalid inputs65- Boundary values (0, -1, empty string, null, max int, etc.)66- Type coercion edge cases if applicable6768### Integration Tests (if the code interacts with other modules)69- Component interactions and data flow70- API calls with mocked responses (success + failure)71- Service layer with mocked dependencies72- State management side effects7374### Edge Cases and Error Handling75- Null, undefined, empty inputs76- Malformed data77- Network failures / timeouts78- Concurrent access / race conditions79- Extremely large inputs8081---8283## Step 4: Write the Tests8485Follow these principles:8687### Structure8889```90describe("[ModuleName]", () => {91 describe("[functionName]", () => {92 it("should [expected behavior] when [condition]", () => {93 // Arrange94 // Act95 // Assert96 });97 });98});99```100101- **Descriptive test names** — Read like documentation: "should return empty array when input is null"102- **AAA pattern** — Arrange (setup), Act (execute), Assert (verify). Separate each visually.103- **One assertion per concept** — Multiple `expect()` calls are fine if they assert one logical thing104- **Group with `describe`** — One block per function/method/component behavior105- **Setup/teardown** — Use `beforeEach`/`afterEach` for test isolation. Clean up subscriptions, timers, mocks.106107### Mocking Strategy108109- Mock **external dependencies only** — Don't mock the code under test110- Use the project's existing mock patterns (e.g., `jest.mock()`, `vi.mock()`, `unittest.mock`)111- Create **test data factories** for complex objects instead of inline literals112- Mock timers (`jest.useFakeTimers()` / `vi.useFakeTimers()`) for time-dependent code113- Mock dates for deterministic snapshots114- Always **restore mocks** in `afterEach` to prevent test pollution115116### Async Testing117118- Always `await` async functions or return the promise119- Test both resolve and reject paths120- Use `waitFor` / `findBy` for async UI updates (React Testing Library)121- Test loading, success, and error states122123### Framework-Specific Guidance124125| Framework | Component Testing | Key Patterns |126|-----------|------------------|--------------|127| **React** | React Testing Library | `render()`, `screen.getByRole()`, `userEvent`, `waitFor` |128| **Vue** | Vue Test Utils | `mount()`, `shallowMount()`, `wrapper.find()`, `trigger()` |129| **Angular** | TestBed | `TestBed.configureTestingModule()`, `fixture.detectChanges()` |130| **Node.js** | Supertest | `request(app).get("/api/...").expect(200)` |131| **Python** | pytest | `@pytest.fixture`, `monkeypatch`, parametrize |132| **Go** | testing | `t.Run()`, table-driven tests, `t.Parallel()` |133134---135136## Step 5: Verify and Improve137138After generating the tests:1391401. **Run the tests** — Execute the test suite to make sure they pass1412. **Check coverage** — Identify untested lines or branches1423. **Add missing cases** — Fill gaps in coverage, especially error paths1434. **Review test quality** — Tests should fail when the code breaks, not just when the tests break144145### Coverage Goals146147| Priority | Coverage Target |148|----------|----------------|149| Critical business logic | 90%+ |150| Utility functions | 85%+ |151| UI components | 80%+ |152| Configuration/glue code | 60%+ |153154Focus on **branch coverage** over line coverage — untested `else` and `catch` paths are where bugs hide.155156---157158## Output Checklist159160Before finishing, verify:161162- [ ] Tests follow the project's existing naming convention and file location163- [ ] All exported functions/components have at least one test164- [ ] Happy path tested for every function165- [ ] Error/failure path tested for every function that can fail166- [ ] Edge cases covered (null, empty, boundary values)167- [ ] External dependencies are mocked (no real API calls, no real DB)168- [ ] Async code is properly awaited169- [ ] Mocks are cleaned up in afterEach170- [ ] Tests are independent — can run in any order171- [ ] Test names read like documentation