CodePark/ questions / Mocks, stubs, spies & fakes
START PRACTICINGPRACTICE
Backend question · Backend testing › Mocks, stubs, spies & fakes

In Jest, what is the difference between jest.clearAllMocks(), jest.resetAllMocks() and jest.restoreAllMocks()?

clear wipes recorded calls and results but keeps implementations; reset also removes implementations such as mockReturnValue; restore puts back the original methods replaced by jest.spyOn

Each one does more than the one before:
•
clearAllMocks resets only mock.calls and mock.results. Stubbed return values stay and carry into the next test.
•
resetAllMocks does the same, and also removes those implementations, such as mockReturnValue.
•
restoreAllMocks undoes jest.spyOn replacements, so the original methods come back.

The config options
clearMocks, resetMocks and restoreMocks do the same thing automatically before every test.

"All three do the same thing; they are aliases kept for backwards compatibility" is wrong: each one has a different effect. "clear wipes recorded calls; reset restores spied methods to their originals..." is also wrong: putting back spied methods is the job of restore, not reset.