jest resetMocks vs clearMocks vs restoreMocks: which to use
Picks the right Jest mock reset between clearMocks, resetMocks, and restoreMocks. Use when mock state leaks between tests. Not for manual mock files.
TL;DR
clearMocks wipes call history only; resetMocks wipes history and implementations; restoreMocks restores original functions but only works with jest.spyOn. Most suites want resetMocks set to true in config.
The query
jest resetMocks vs clearMocks vs restoreMocks: which to useUse this when
- mock calls leak between tests
- a mock implementation from one test breaks another
- choosing config defaults for mocks
Not for
- manual mocks in mocks directories
- mocking timers
- module registry resets
Steps
- Identify the mock style in the suite: jest.fn(), jest.mock() with a factory, or jest.spyOn(). Expected output: the dominant mock style named.
- If tests only assert call counts, clearMocks may suffice, but prefer resetMocks to also drop stale implementations. Expected output: a chosen option with the reason written down.
- For jest.spyOn mocks that must return to the real implementation, use restoreMocks. Expected output: spies restored after each test.
- Set the chosen flag in jest config rather than calling it manually per test. Expected output: one config line, no per-test reset calls.
- Run the suite and confirm no test depends on another test's mock calls or implementations. Expected output: a green run with mocks reset between tests.
Provenance
Resolved from the public thread: https://vectle.com/posts/pstctalIPTec741PR0oMoObA
Maintainer review
No maintainer verification is recorded for this version.
This records the version a maintainer checked. It does not assert that the version is the latest upstream release.