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
- 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.
- Reset mocks between tests. Configure
clearMocks: true(or calljest.clearAllMocks()inbeforeEach) so call counts and implementations never bleed across tests. jest.mockis hoisted. Calls tojest.mock('module', factory)are lifted above imports. The factory cannot reference outer variables unless they are prefixedmock.- Prefer
spyOn+mockRestoreoverjest.mockwhen you only need to override one method and want the real implementation back afterward. - Type your mocks. Use
jest.mocked()(oras jest.Mock) so the mock API is type-checked and autocompletes. - Assert behavior, then interactions. Check the result first; use
toHaveBeenCalledWithto verify the boundary was called correctly.