Prerequisites
Before using this skill, ensure you have:
- Source code files requiring test coverage
- Testing framework installed (Jest, Mocha, pytest, JUnit, etc.)
- Understanding of code dependencies and external services to mock
- Test directory structure established (e.g.,
tests/, __tests__/, spec/)
- Package configuration updated with test scripts
Instructions
Step 1: Analyze Source Code
Examine code structure and identify test requirements:
- Use Read tool to load source files from {baseDir}/src/
- Identify all functions, classes, and methods requiring tests
- Document function signatures, parameters, return types, and side effects
- Note external dependencies requiring mocking or stubbing
Step 2: Determine Testing Framework
Select appropriate testing framework based on language:
- JavaScript/TypeScript: Jest, Mocha, Jasmine, Vitest
- Python: pytest, unittest, nose2
- Java: JUnit 5, TestNG
- Go: testing package with testify assertions
- Ruby: RSpec, Minitest
Step 3: Generate Test Cases
Create comprehensive test suite covering:
- Happy path tests with valid inputs and expected outputs
- Edge case tests with boundary values (empty arrays, null, zero, max values)
- Error condition tests with invalid inputs
- Mock external dependencies (databases, APIs, file systems)
- Setup and teardown fixtures for test isolation
Step 4: Write Test File
Generate test file in {baseDir}/tests/ with structure:
- Import statements for code under test and testing framework
- Mock declarations for external dependencies
- Describe/context blocks grouping related tests
- Individual test cases with arrange-act-assert pattern
- Cleanup logic in afterEach/tearDown hooks
Output
The skill generates complete test files:
Test File Structure
// Example Jest test file
import { validator } from '../src/utils/validator';
describe('Validator', () => {
describe('validateEmail', () => {
it('should accept valid email addresses', () => {
expect(validator.validateEmail('test@example.com')).toBe(true);
});
it('should reject invalid email formats', () => {
expect(validator.validateEmail('invalid-email')).toBe(false);
});
it('should handle null and undefined', () => {
expect(validator.validateEmail(null)).toBe(false);
expect(validator.validateEmail(undefined)).toBe(false);
});
});
});
Coverage Metrics
- Line coverage percentage (target: 80%+)
- Branch coverage showing tested conditional paths
- Function coverage ensuring all exports are tested
- Statement coverage for comprehensive validation
Mock Implementations
Generated mocks for:
- Database connections and queries
- HTTP requests to external APIs
- File system operations (read/write)
- Environment variables and configuration
- Time-dependent functions (Date.now(), setTimeout)
Error Handling
Common issues and solutions:
Module Import Errors
- Error: Cannot find module or dependencies
- Solution: Install missing packages; verify import paths match project structure; check TypeScript configuration
Mock Setup Failures
- Error: Mock not properly intercepting calls
- Solution: Ensure mocks are defined before imports; use proper mocking syntax for framework; clear mocks between tests
Async Test Timeouts
- Error: Test exceeded timeout before completing
- Solution: Increase timeout for slow operations; ensure async/await or done callbacks are used correctly; check for unresolved promises
Test Isolation Issues
- Error: Tests pass individually but fail when run together
- Solution: Add proper cleanup in afterEach hooks; avoid shared mutable state; reset mocks between tests
Resources
Testing Frameworks
- Jest documentation for JavaScript testing
- pytest documentation for Python testing
- JUnit 5 User Guide for Java testing
- Go testing package and testify library
Best Practices
- Follow AAA pattern (Arrange, Act, Assert) for test structure
- Write tests before fixing bugs (test-driven bug fixing)
- Use descriptive test names that explain the scenario
- Keep tests independent and avoid test interdependencies
- Mock external dependencies for unit test isolation
- Aim for 80%+ code coverage on critical paths
1---2name: generating-unit-tests3description: 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".4license: MIT5---6## Prerequisites78Before using this skill, ensure you have:9- Source code files requiring test coverage10- Testing framework installed (Jest, Mocha, pytest, JUnit, etc.)11- Understanding of code dependencies and external services to mock12- Test directory structure established (e.g., `tests/`, `__tests__/`, `spec/`)13- Package configuration updated with test scripts1415## Instructions1617### Step 1: Analyze Source Code18Examine code structure and identify test requirements:191. Use Read tool to load source files from {baseDir}/src/202. Identify all functions, classes, and methods requiring tests213. Document function signatures, parameters, return types, and side effects224. Note external dependencies requiring mocking or stubbing2324### Step 2: Determine Testing Framework25Select appropriate testing framework based on language:26- JavaScript/TypeScript: Jest, Mocha, Jasmine, Vitest27- Python: pytest, unittest, nose228- Java: JUnit 5, TestNG29- Go: testing package with testify assertions30- Ruby: RSpec, Minitest3132### Step 3: Generate Test Cases33Create comprehensive test suite covering:341. Happy path tests with valid inputs and expected outputs352. Edge case tests with boundary values (empty arrays, null, zero, max values)363. Error condition tests with invalid inputs374. Mock external dependencies (databases, APIs, file systems)385. Setup and teardown fixtures for test isolation3940### Step 4: Write Test File41Generate test file in {baseDir}/tests/ with structure:42- Import statements for code under test and testing framework43- Mock declarations for external dependencies44- Describe/context blocks grouping related tests45- Individual test cases with arrange-act-assert pattern46- Cleanup logic in afterEach/tearDown hooks4748## Output4950The skill generates complete test files:5152### Test File Structure53```javascript54// Example Jest test file55import { validator } from '../src/utils/validator';5657describe('Validator', () => {58 describe('validateEmail', () => {59 it('should accept valid email addresses', () => {60 expect(validator.validateEmail('test@example.com')).toBe(true);61 });6263 it('should reject invalid email formats', () => {64 expect(validator.validateEmail('invalid-email')).toBe(false);65 });6667 it('should handle null and undefined', () => {68 expect(validator.validateEmail(null)).toBe(false);69 expect(validator.validateEmail(undefined)).toBe(false);70 });71 });72});73```7475### Coverage Metrics76- Line coverage percentage (target: 80%+)77- Branch coverage showing tested conditional paths78- Function coverage ensuring all exports are tested79- Statement coverage for comprehensive validation8081### Mock Implementations82Generated mocks for:83- Database connections and queries84- HTTP requests to external APIs85- File system operations (read/write)86- Environment variables and configuration87- Time-dependent functions (Date.now(), setTimeout)8889## Error Handling9091Common issues and solutions:9293**Module Import Errors**94- Error: Cannot find module or dependencies95- Solution: Install missing packages; verify import paths match project structure; check TypeScript configuration9697**Mock Setup Failures**98- Error: Mock not properly intercepting calls99- Solution: Ensure mocks are defined before imports; use proper mocking syntax for framework; clear mocks between tests100101**Async Test Timeouts**102- Error: Test exceeded timeout before completing103- Solution: Increase timeout for slow operations; ensure async/await or done callbacks are used correctly; check for unresolved promises104105**Test Isolation Issues**106- Error: Tests pass individually but fail when run together107- Solution: Add proper cleanup in afterEach hooks; avoid shared mutable state; reset mocks between tests108109## Resources110111### Testing Frameworks112- Jest documentation for JavaScript testing113- pytest documentation for Python testing114- JUnit 5 User Guide for Java testing115- Go testing package and testify library116117### Best Practices118- Follow AAA pattern (Arrange, Act, Assert) for test structure119- Write tests before fixing bugs (test-driven bug fixing)120- Use descriptive test names that explain the scenario121- Keep tests independent and avoid test interdependencies122- Mock external dependencies for unit test isolation123- Aim for 80%+ code coverage on critical paths