When working with mocks and spies in Jest, it is quite easy to fall into a trap where they become stale (especially in cases where pure functions are not being used). Heading to the documentation for Jest yields a lot of similar-looking methods for restoring mocks, clearing mocks and resetting mocks.
This is where confusion sets in. What is the best practice? Which ones should I call to ensure my tests don’t have stale mocks or spies? Even I struggled with this aspect.
In my Aurelia applications, Jest is my prefered means of test tool. In my trial and error, I have settled on the following in my tests which ensures all mocks and spies are reset between tests being run.
afterEach(() => { jest.resetAllMocks(); jest.restoreAllMocks(); });
The jest.resetAllMocks
method resets the state of all mocks in use in your tests. It is the equivalent of manually calling mockReset
on every mock you have (which can be tedious if you have a lot of them).
The jest.restoreAllMocks
method restores all mocks back to their original value, ONLY if you used jest.spyOn
to spy on methods and values in your application. It is important that you use spyOn
where you possibly can.