Generate a Comprehensive Jest Unit Test Suite for JavaScript Functions
Create a thorough Jest unit test suite with mocks, edge cases, error paths, and data-driven tests for your JavaScript module.
๐ The Prompt
Write a complete Jest unit test suite for a [LANGUAGE] module called [MODULE_NAME] that handles [MODULE_PURPOSE]. The module exports the following functions:
[LIST_FUNCTIONS_WITH_SIGNATURES_AND_DESCRIPTIONS]
Generate the test suite following this structure:
1. **Test File Setup**:
- Import/require the module under test
- Set up any mocks for [EXTERNAL_DEPENDENCIES] using jest.mock()
- Define shared test fixtures and factory functions in a beforeAll/beforeEach block
- Add afterEach cleanup to restore mocks via jest.restoreAllMocks()
2. **Describe Blocks**: Organize tests using nested describe blocks grouped by function name. For each function, include:
- **Happy Path Tests** (at least 3): Verify correct output for valid inputs including edge cases like empty arrays, zero values, and boundary conditions
- **Error Path Tests** (at least 2): Verify proper error throwing or rejection for invalid inputs such as null, undefined, wrong types, and out-of-range values
- **Async Tests** (if applicable): Use async/await with expect().resolves and expect().rejects
- **Mock Verification**: Assert that [EXTERNAL_DEPENDENCIES] were called with expected arguments using toHaveBeenCalledWith()
3. **Test Patterns**:
- Use test.each() for data-driven tests where [PARAMETRIZE_SCENARIO]
- Include snapshot tests if the function returns complex objects
- Add a test for idempotency or side-effect isolation where relevant
4. **Coverage Goals**: Ensure the suite targets [COVERAGE_PERCENTAGE]% branch coverage. Add comments noting any intentionally uncovered branches.
Use descriptive test names following the pattern: 'should [expected behavior] when [condition]'. Include inline comments explaining non-obvious test logic.
๐ก Tips for Better Results
Provide the actual function signatures and their expected behaviors to get precise assertions. Mention all external dependencies (databases, APIs, file system) so the AI generates appropriate mocks. Specify your Jest version if you need compatibility with specific APIs like jest.mocked().
๐ฏ Use Cases
Frontend and backend JavaScript developers use this when building a test suite for new or existing modules to achieve high code coverage and catch regressions early.