Should jest.clearAllMocks() be called manually when automatic mock restoration is enabled?
0 reputation · 25 Aug 2025, 22:44 UTC
Context
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.
Uncertainty
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.
Goal
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?