I\'m trying to wrap my head around the following in Jest:
resetAllMocks
, resetModules
, resetModuleRegistry
and restoreA
The following sections explain the behaviors of each function and its corresponding config directive. In the case of config directives, the explained behavior takes place in between each test making them more and more isolated from the other tests.
References to fn
are implying a sample jest mock function under each of these actions.
jest.clearAllMocks()
and clearMocks:[boolean]
Resets all the mocks usage data, not their implementation. In other words, it only replaces fn.mock.calls
and fn.mock.instances
properties of a jest mock function.
jest.resetAllMocks()
and the resetMocks:[boolean]
A superset of clearAllMocks()
which also takes care of resetting the implementation to a no return
function. In other words, it will replace the mock function with a new jest.fn()
, not just its fn.mock.calls
and fn.mock.instances
.
jest.restoreAllMocks()
and restoreMocks:[boolean]
Similar to resetAllMocks()
, with one very important difference. It restores the original implementation of "spies". So, it goes like "replace mocks with jest.fn(), but replace spies with their original implementation".
So, in cases where we manually assign things with jest.fn() (not spies), we have to take care of implementation restoration ourselves as jest won't be doing it.
jest.resetModules()
and resetModules:[boolean]
It resets Jest's module registry which is a cache for all required/imported modules. Jest will re-import any required module after a call to this. Imagine a clean slate without having to deal with all the mocked out modules in other tests.
jest.resetModuleRegistry
It's just an alias for resetModules
, see:
https://github.com/facebook/jest/blob/7f69176c/packages/jest-runtime/src/index.ts#L1147
See how clearing, resetting and restoring differ in action:
https://repl.it/@sepehr/jest-mock-api-reset-restore#jest-mock-apis.test.js