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 filter
  • should throw error when input is negative
  • should call callback with correct parameters

Bad names:

  • test1
  • it works
  • should work correctly

Test Quality Guidelines

  1. Independence: Tests should not depend on each other
  2. Repeatability: Tests should produce same results every time
  3. Fast: Unit tests should run quickly
  4. Isolated: Use mocks/stubs for external dependencies
  5. Clear: Test intent should be obvious
  6. Comprehensive: Cover all code paths
  7. 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:

  1. Complete test suite with all necessary imports
  2. Setup/teardown if needed
  3. Mock configurations
  4. Clear test descriptions
  5. Comments explaining complex test scenarios
  6. Assertion explanations where helpful

Generate a complete, production-ready test suite following these best practices.