generating-unit-tests
Test automatically generate comprehensive unit tests from source code covering happy paths, edge cases, and error conditions. Use when creating test coverage for functions, classes, or modules. Trigger with phrases like "generate unit tests", "create tests for", or "add test coverage".
What this skill does
# Unit Test Generator
## Overview
Automatically generate comprehensive unit tests from source code analysis covering happy paths, edge cases, boundary conditions, and error handling. Supports Jest, Vitest, Mocha (JavaScript/TypeScript), pytest (Python), JUnit 5 (Java), and Go testing with testify.
## Prerequisites
- Testing framework installed and configured (`jest`, `vitest`, `pytest`, `junit-jupiter`, or Go `testing`)
- Source code with clear function signatures, type annotations, or JSDoc comments
- Test directory structure established (`__tests__/`, `tests/`, `spec/`, or `*_test.go`)
- Mocking library available (`jest.mock`, `unittest.mock`, `Mockito`, or `gomock`)
- Package scripts configured to run tests (`npm test`, `pytest`, `go test`)
## Instructions
1. Scan the codebase with Glob to locate source files that lack corresponding test files (e.g., `src/utils/parser.ts` without `__tests__/parser.test.ts`).
2. Read each untested source file and extract:
- All exported functions and class methods with their signatures.
- Parameter types, return types, and thrown exceptions.
- External dependencies (imports from other modules, third-party libraries, I/O).
- Pure vs. impure function classification.
3. For each function, generate test cases in these categories:
- **Happy path**: Valid inputs producing expected outputs (at least 2 cases).
- **Edge cases**: Empty strings, empty arrays, zero, negative numbers, `null`, `undefined`, maximum values.
- **Error conditions**: Invalid types, missing required fields, network failures, permission errors.
- **Boundary values**: Off-by-one, integer overflow, string length limits.
4. Create mock declarations for all external dependencies:
- Database calls return predictable fixture data.
- HTTP clients return canned responses with configurable status codes.
- File system operations use in-memory buffers or temp directories.
5. Write the test file following project conventions:
- Match the existing test file naming pattern (`*.test.ts`, `*.spec.js`, `test_*.py`).
- Group tests in `describe`/`context` blocks by function name.
- Use `beforeEach`/`afterEach` for setup and teardown.
- Include inline comments explaining non-obvious test rationale.
6. Run the generated tests to verify they pass, then check coverage to confirm the target function is fully exercised.
7. Report coverage gaps and suggest additional test cases for uncovered branches.
## Output
- Test files placed alongside source files or in the project's test directory
- Mock/stub files for external dependencies
- Coverage report showing line, branch, and function coverage for tested modules
- List of remaining coverage gaps with suggested test cases
## Error Handling
| Error | Cause | Solution |
|-------|-------|---------|
| `Cannot find module` on import | Test file path does not match project module resolution | Check `tsconfig.json` paths and `moduleNameMapper` in Jest config |
| Mock not intercepting calls | Mock defined after module import caches the real implementation | Move `jest.mock()` calls to the top of the file before any imports |
| Async test timeout | Promise never resolves due to missing `await` or unhandled rejection | Add `await` before async calls; increase timeout with `jest.setTimeout()` |
| Tests pass alone but fail together | Shared mutable state leaking between tests | Reset state in `afterEach`; avoid module-level variables; use `jest.isolateModules()` |
| Snapshot mismatch on first run | No existing snapshot baseline | Run with `--updateSnapshot` on first execution to create the baseline |
## Examples
**Jest test for a string utility:**
```typescript
import { slugify } from '../src/utils/slugify';
describe('slugify', () => {
it('converts spaces to hyphens', () => {
expect(slugify('hello world')).toBe('hello-world');
});
it('lowercases all characters', () => {
expect(slugify('Hello World')).toBe('hello-world');
});
it('removes special characters', () => {
expect(slugify('hello@world!')).toBe('helloworld');
});
it('handles empty string', () => {
expect(slugify('')).toBe('');
});
it('trims leading and trailing whitespace', () => {
expect(slugify(' spaced ')).toBe('spaced');
});
});
```
**pytest test for a data validator:**
```python
import pytest
from myapp.validators import validate_email
class TestValidateEmail:
def test_accepts_valid_email(self):
assert validate_email("[email protected]") is True
def test_rejects_missing_at_sign(self):
assert validate_email("userexample.com") is False
def test_rejects_empty_string(self):
assert validate_email("") is False
def test_rejects_none(self):
with pytest.raises(TypeError):
validate_email(None)
```
## Resources
- Jest documentation: https://jestjs.io/docs/getting-started
- Vitest documentation: https://vitest.dev/guide/
- pytest documentation: https://docs.pytest.org/
- JUnit 5 User Guide: https://junit.org/junit5/docs/current/user-guide/
- Go testing package: https://pkg.go.dev/testing
- AAA pattern (Arrange-Act-Assert):
Related in Code Review
gstack
IncludedFast headless browser for QA testing and site dogfooding. Navigate pages, interact with elements, verify state, diff before/after, take annotated screenshots, test responsive layouts, forms, uploads, dialogs, and capture bug evidence. Use when asked to open or test a site, verify a deployment, dogfood a user flow, or file a bug with screenshots. (gstack)
startup-due-diligence
IncludedLegal due diligence review for seed-stage and Series A startups (US, Delaware C-Corp focus). Supports both investor and founder perspectives. Capabilities include: (1) Interactive document review and issue spotting; (2) Document request list generation; (3) Cap table and SAFE/convertible note analysis; (4) Red flag identification with severity ratings; (5) Diligence report generation. TRIGGERS: due diligence, DD, startup investment, cap table review, Series A, seed round, investor diligence, legal review startup, SAFE analysis, convertible note, 409A, founder vesting.
interview-master
IncludedThis skill should be used when the user asks to "generate interview questions", "prepare for interview", "optimize resume", "conduct mock interview", "analyze git commits for resume", "generate resume from code", "review my resume", or mentions interview preparation, career assistance, or extracting project experience from git history. Provides comprehensive interview and career development guidance for both job seekers and interviewers.
fix-issue
IncludedFixes GitHub issues using parallel analysis agents for root cause investigation, code exploration, and regression detection. Reads issue context from gh CLI, searches codebase and memory for related patterns, generates a fix with tests, and links the resolution back to the issue via PR. Includes prevention analysis to avoid recurrence. Use when debugging errors, resolving regressions, fixing bugs, or triaging issues.
sf-apex
IncludedGenerates and reviews Salesforce Apex code with 150-point scoring. TRIGGER when: user writes, reviews, or fixes Apex classes, triggers, test classes, batch/queueable/schedulable jobs, or touches .cls/.trigger files. DO NOT TRIGGER when: LWC JavaScript (use sf-lwc), Flow XML (use sf-flow), SOQL-only queries (use sf-soql), or non-Salesforce code.
swift-development
IncludedComprehensive Swift development for building, testing, and deploying iOS/macOS applications. Use when Claude needs to: (1) Build Swift packages or Xcode projects from command line, (2) Run tests with XCTest or Swift Testing framework, (3) Manage iOS simulators with simctl, (4) Handle code signing, provisioning profiles, and app distribution, (5) Format or lint Swift code with SwiftFormat/SwiftLint, (6) Work with Swift Package Manager (SPM), (7) Implement Swift 6 concurrency patterns (async/await, actors, Sendable), (8) Create SwiftUI views with MVVM architecture, (9) Set up Core Data or SwiftData persistence, or any other Swift/iOS/macOS development tasks.