Jest Unit Testing Best Practices

testing
TypeScript
testing
zen
Remix

Comprehensive unit testing guide using Jest with mocking, coverage, and TDD patterns.

12/8/2025

Prompt

Generate a comprehensive Jest unit test suite for the following code with complete coverage, mocking, and best practices:

Code to Test

Target Files/Modules

Provide the code to test:

  • Primary Module: [File path or code snippet to test]
  • Module Type: [Service / API handler / Utility / Component / Class / Function]
  • Dependencies: [List external dependencies: database, APIs, services, etc.]
  • Language: [TypeScript / JavaScript]

Module Details

  • Module Name: [e.g., UserService, AuthController, PaymentProcessor]
  • Primary Functions/Methods: [List 3-10 functions to test]
  • External Dependencies: [Database, APIs, file system, third-party libraries]
  • Side Effects: [Database writes, API calls, file operations, etc.]

Testing Requirements

Test Coverage Goals

  • Target Coverage: [80% / 90% / 100% / Specific percentage]
  • Coverage Types:
    • Line coverage
    • Branch coverage
    • Function coverage
    • Statement coverage
  • Critical Paths: [List must-test scenarios]

Test Categories

1. Happy Path Tests

For each function, test:

  • Valid Inputs: [Expected successful scenarios]
  • Expected Outputs: [What should be returned/changed]
  • Side Effects: [Database changes, API calls, etc.]

2. Error Handling Tests

For each function, test:

  • Invalid Inputs: [Null, undefined, wrong types, out of range]
  • Expected Errors: [Error types and messages]
  • Error Recovery: [Cleanup, rollback, logging]

3. Edge Cases

Test boundary conditions:

  • Empty Values: [Empty strings, arrays, objects]
  • Null/Undefined: [Missing optional parameters]
  • Extreme Values: [Very large numbers, long strings]
  • Concurrent Operations: [Race conditions if applicable]

4. Integration Points

Test interactions with:

  • Database: [CRUD operations, transactions, constraints]
  • External APIs: [Success, failures, timeouts]
  • File System: [Read/write operations if applicable]
  • Other Services: [Internal service calls]

Mocking Strategy

Dependencies to Mock

For each external dependency:

Dependency 1: [Name, e.g., Prisma, Database]

  • Mock Type: [Full mock / Partial mock / Spy]
  • Mock Behavior: [Return values, errors, delays]
  • Mock Data: [Sample data to return]

Dependency 2: [Name, e.g., External API]

  • Mock Type: [Full mock / Partial mock / Spy]
  • Mock Behavior: [Success responses, error responses, timeouts]
  • Mock Data: [Sample API responses]

Dependency 3: [Name, e.g., Email service, File system]

  • Mock Type: [Full mock / Partial mock / Spy]
  • Mock Behavior: [Expected behavior]
  • Mock Data: [Sample data]

Mock Implementations

  • Module Mocks: [Which modules to mock with jest.mock()]
  • Function Mocks: [Which functions need jest.fn()]
  • Spy Usage: [Which functions to spy on with jest.spyOn()]
  • Mock Timers: [setTimeout, setInterval if needed]

Test Structure

Organization

  • Test File Naming: [filename.test.ts / filename.spec.ts]
  • Describe Blocks: [Nested by module/class/function]
  • Test Grouping: [Group related tests together]
  • Test Naming: [Descriptive "should..." format]

Setup and Teardown

  • beforeAll: [One-time setup: database connection, etc.]
  • beforeEach: [Per-test setup: clear mocks, reset state]
  • afterEach: [Per-test cleanup: clear data, reset mocks]
  • afterAll: [One-time cleanup: close connections, etc.]

Async Testing Requirements

  • Async Functions: [List async functions to test]
  • Testing Method: [async/await / Promise chains / done callback]
  • Timeout Handling: [Custom timeouts for slow operations]
  • Concurrent Tests: [Can tests run in parallel or need isolation?]

Assertions and Matchers

Expected Assertions

For each test, specify:

  • Return Value Checks: [toBe, toEqual, toMatchObject]
  • Type Checks: [toBeInstanceOf, typeof checks]
  • Array/Object Checks: [toContain, toHaveProperty, toHaveLength]
  • Error Checks: [toThrow, rejects.toThrow]
  • Mock Checks: [toHaveBeenCalled, toHaveBeenCalledWith]

Custom Matchers (if needed)

  • Custom Assertions: [Any domain-specific matchers needed]

Test Data

Fixtures

  • Valid Test Data: [Sample valid inputs for happy path]
  • Invalid Test Data: [Sample invalid inputs for error cases]
  • Edge Case Data: [Boundary values, empty values, etc.]
  • Mock Responses: [Sample API/database responses]

Data Factories (if needed)

  • Factory Functions: [Generate test data dynamically]
  • Builders: [Test data builders for complex objects]

Performance and Optimization

Test Performance

  • Parallel Execution: [Can tests run in parallel?]
  • Test Isolation: [Each test independent or shared state?]
  • Mock Optimization: [Reuse mocks or create fresh each time?]
  • Cleanup Strategy: [How to clean up after tests?]

Code Generation Requirements

Generate a complete Jest test suite including:

  1. Test File Setup:

    • Proper imports for Jest, testing utilities, and module under test
    • Mock declarations at the top of file
    • Type definitions for TypeScript
    • Test configuration if needed
  2. Mock Implementations:

    • Complete mocks for all external dependencies
    • Mock data factories for test fixtures
    • Mock function implementations with proper return values
    • Spy setup for functions that need observation
  3. Test Suites (describe blocks):

    • Organized by module/class/function hierarchy
    • Nested describe blocks for logical grouping
    • Clear, descriptive test suite names
  4. Setup and Teardown:

    • beforeAll for one-time setup
    • beforeEach for per-test initialization and mock clearing
    • afterEach for per-test cleanup
    • afterAll for final cleanup
  5. Test Cases (it/test blocks):

    • Happy path tests for all functions
    • Error handling tests for all failure scenarios
    • Edge case tests for boundary conditions
    • Integration tests for dependency interactions
    • Async tests with proper async/await handling
  6. Assertions:

    • Comprehensive expect statements
    • Proper matchers for each assertion type
    • Mock verification (toHaveBeenCalled, etc.)
    • Error assertion with proper error messages
  7. Test Utilities:

    • Helper functions for common test operations
    • Data factories for generating test data
    • Custom matchers if needed
    • Shared test fixtures
  8. Documentation:

    • Comments explaining complex test scenarios
    • Documentation for test data factories
    • Instructions for running tests
    • Coverage report interpretation
  9. Jest Configuration (if needed):

    • jest.config.js with proper settings
    • Coverage thresholds
    • Test environment setup
    • Module path mappings

Output production-ready Jest tests following best practices with:

  • Complete code coverage for all functions
  • Proper mocking of all external dependencies
  • Clear, descriptive test names using "should..." format
  • Comprehensive assertions for all scenarios
  • Proper async/await handling
  • Clean setup and teardown
  • Test isolation (no shared state between tests)
  • Fast execution with optimized mocks
  • Type-safe TypeScript tests
  • AAA pattern (Arrange, Act, Assert)

Tags

jest
unit-testing
tdd
mocking

Tested Models

gpt-4
claude-3-5-sonnet

Comments (0)

Sign in to leave a comment

Sign In