๐งผ cleaning up jest mocks
In jest, there are three different ways to clean up a mock function.
Each different method cleans up a different subset of functionality, with mockClear
being the least destructive and mockReset
being the most destructive.
mock clear
Running this function removes all the statistics about invocations of the mock function. It sets all of the properties to their default value of []
.
Typically you would want to run mockClear
between tests that all require the same mock functionality. This allows you to start each test with a clean slate when it comes to invocations so you can make accurate assertions on how many times functions were called with what data.
mock reset
Executing this method resets all of the invocation statistics, and also gets rid of any mocked functionality, like return values or implementations.
You could use mockReset
in between tests that require different data returned from a mock function. Each test would then declare what data it expects from the mock to make assertions later on.
mock restore
Executing this function acts like you never called jest.mock()
in the first place. It restores the original functionality of the method, wipes any mock functionality, and removes all invocation statistics.
Restoring mocks can be helpful when some tests require mock functionality and others do not.