Should jest.clearAllMocks() be called manually when automatic mock restoration is enabled?
0 reputation · 25 Aug 2025, 22:44 UTC
0 reputation · 25 Aug 2025, 22:44 UTC
Jest 27.0.6 introduced an explicit cleanup step during test environment teardown that deletes mock registry entries, resolving a memory leak observed when jest.spyOn combined with mockImplementationOnce was used repeatedly in watch mode. Automatic mock restoration between tests has been a documented feature since earlier versions, yet the official guidance does not state whether developers should still invoke jest.clearAllMocks() in afterEach hooks.
Projects upgrading across Jest 24–27 boundaries may see different restoration behavior. In long-running watch or CI processes that reuse the Jest process, residual mock references could still accumulate if the automatic restoration does not cover every registry entry. The documentation leaves the decision open, creating inconsistency across codebases.
Determine whether manual jest.clearAllMocks() calls provide measurable benefit over relying solely on the built‑in restoration, and under what conditions the extra cleanup is warranted.
Does the automatic restoration fully clear the internal mock registry for all mock types?
When, if ever, does adding jest.clearAllMocks() in afterEach reduce memory retention in watch mode?
Which Jest versions exhibit a measurable difference between the two approaches?
31275 reputation · 26 Aug 2025, 06:17 UTC
No, calling jest.clearAllMocks() in afterEach is not required when automatic mock restoration is enabled, but it can reduce memory retention in watch mode when jest.spyOn is used extensively.
jest.spyOn with mockImplementationOnce, may not be fully purged.spyOn/mockImplementationOnce.jest.fn() and jest.spyOn(); spyOn retains spy-specific state that automatic restoration may not fully erase.clearAllMocks() in afterEach measurably reduces memory retention in watch mode when spyOn is extensive, but is generally unnecessary for fn-based mocks or when the Jest process restarts each run.If your project uses jest.spyOn in watch mode and observes growing memory usage between test cycles, adding jest.clearAllMocks() in afterEach is a pragmatic safeguard. Otherwise, automatic restoration alone typically suffices.
Verification step: Run the same test suite in watch mode with and without an afterEach hook that calls jest.clearAllMocks(). Use Jest internal output or a heap snapshot tool to compare mock registry size or process memory between runs. If memory growth stops or decreases with the hook, the cleanup provides measurable benefit for your setup.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.