Generate Unit Tests
Generate Unit Tests
Generates comprehensive unit tests for supplied code, covering happy paths, edge cases, error handling, parameterized tests, and framework-specific examples.
How to use
Replace {{args}} with your code snippet, file path, function or repository link to generate framework-tailored unit tests and examples.
Prompt
Generate Unit Tests
Please create comprehensive unit tests for the following code:
{{args}}
Test Framework Considerations
Adapt to the appropriate testing framework:
- JavaScript/TypeScript: Jest, Vitest, Mocha
- Python: pytest, unittest
- Java: JUnit
- C#: xUnit, NUnit
- Go: testing package
- Ruby: RSpec
- PHP: PHPUnit
Test Structure
1. Test Organization
describe('FunctionName' or 'ClassName', () => {
describe('methodName', () => {
it('should handle normal case', () => {});
it('should handle edge case', () => {});
it('should throw error for invalid input', () => {});
});
});2. Test Coverage Areas
Happy Path Tests
Test normal, expected behavior:
- Valid inputs with expected outputs
- Common use cases
- Typical workflows
Edge Cases
Test boundary conditions:
- Empty inputs (null, undefined, empty string, empty array)
- Zero values
- Negative numbers
- Very large numbers
- Maximum/minimum values
- Single element collections
Error Cases
Test error handling:
- Invalid inputs
- Type mismatches
- Out of range values
- Missing required parameters
- Malformed data
Boundary Conditions
- First and last elements
- Off-by-one scenarios
- Limits and thresholds
3. Test Patterns
Arrange-Act-Assert (AAA)
it('should calculate total with discount', () => {
// Arrange
const price = 100;
const discount = 0.2;
// Act
const result = calculateTotal(price, discount);
// Assert
expect(result).toBe(80);
});Given-When-Then (BDD style)
it('should calculate total with discount', () => {
// Given
const price = 100;
const discount = 0.2;
// When
const result = calculateTotal(price, discount);
// Then
expect(result).toBe(80);
});4. Test Types to Include
Basic Functionality Tests
it('should return correct value for valid input', () => {
expect(add(2, 3)).toBe(5);
});Parameterized Tests
it.each([
[2, 3, 5],
[0, 0, 0],
[-1, 1, 0],
[100, 200, 300]
])('should add %i and %i to equal %i', (a, b, expected) => {
expect(add(a, b)).toBe(expected);
});Async Tests
it('should fetch user data', async () => {
const user = await fetchUser(1);
expect(user.id).toBe(1);
});Mock/Stub Tests
it('should call API with correct parameters', () => {
const mockApi = jest.fn();
service.setApi(mockApi);
service.fetchData(123);
expect(mockApi).toHaveBeenCalledWith(123);
});State Tests
it('should update state correctly', () => {
const obj = new MyClass();
obj.setValue(10);
expect(obj.getValue()).toBe(10);
});5. Setup and Teardown
describe('Database operations', () => {
beforeAll(() => {
// Setup before all tests
});
beforeEach(() => {
// Setup before each test
});
afterEach(() => {
// Cleanup after each test
});
afterAll(() => {
// Cleanup after all tests
});
});6. Test Naming
Use descriptive names that explain:
- What is being tested
- Under what conditions
- What the expected result is
Good names:
should return empty array when no items match filtershould throw error when input is negativeshould call callback with correct parameters
Bad names:
test1it worksshould work correctly
Test Quality Guidelines
- Independence: Tests should not depend on each other
- Repeatability: Tests should produce same results every time
- Fast: Unit tests should run quickly
- Isolated: Use mocks/stubs for external dependencies
- Clear: Test intent should be obvious
- Comprehensive: Cover all code paths
- Maintainable: Easy to update when code changes
Coverage Goals
Aim to test:
- All public methods/functions
- All branches (if/else)
- All error paths
- All edge cases
- All important combinations
Output Format
Provide:
- Complete test suite with all necessary imports
- Setup/teardown if needed
- Mock configurations
- Clear test descriptions
- Comments explaining complex test scenarios
- Assertion explanations where helpful
Generate a complete, production-ready test suite following these best practices.