Jest Mocking Patterns

Installation
SKILL.md

Jest Mocking Patterns

This skill makes the agent mock dependencies in Jest deliberately and reversibly: stubbing functions with jest.fn, controlling return values with mockReturnValue/mockResolvedValue, replacing whole modules with jest.mock factories, and spying on real implementations with jest.spyOn (always restored). The guiding rule: mock the boundary, not the unit under test, and always reset state between tests so mocks never leak.

Use this skill when the agent needs to isolate code from the network, the clock, the filesystem, a database client, or any third-party module (axios, fs, a payment SDK).

Core Principles

  1. Mock at the boundary. Mock network/DB/3rd-party clients, not the function you are testing. If you mock the thing under test, the test proves nothing.
  2. Reset mocks between tests. Configure clearMocks: true (or call jest.clearAllMocks() in beforeEach) so call counts and implementations never bleed across tests.
  3. jest.mock is hoisted. Calls to jest.mock('module', factory) are lifted above imports. The factory cannot reference outer variables unless they are prefixed mock.
  4. Prefer spyOn + mockRestore over jest.mock when you only need to override one method and want the real implementation back afterward.
  5. Type your mocks. Use jest.mocked() (or as jest.Mock) so the mock API is type-checked and autocompletes.
  6. Assert behavior, then interactions. Check the result first; use toHaveBeenCalledWith to verify the boundary was called correctly.

Workflow / Patterns

Pattern 1 — jest.fn and controlling return values

Installs
GitHub Stars
226
First Seen
Jest Mocking Patterns — pramoddutta/qaskills