jest.mock
is hoisted above import
when used at top level and hoisted to the the beginning of the block when used in a block (test function scope, etc), same for jest.unmock
. jest.doMock
and jest.dontMock
serve the same purpose but aren’t hoisted.
This would matter for a case like this one:
it('should mock the module a single time', () => {
let originalHighCharts = require('.../HighCharts');
...
jest.doMock('.../HighCharts', ...);
let mockedHighCharts = require('.../HighCharts');
...
})
That doMock
allows for specific order is rarely useful in practice because mocked module can be retrieved with jest.requireActual
, while the same sequence may not affect other modules that depend on mocked module because of caching.
That doMock
and dontMock
aren’t hoisted allows to use them together for a specified scenario to mock a module for single test:
let HighCharts;
jest.isolateModules(() => {
jest.doMock('.../HighCharts', ...);;
HighCharts = require('.../HighCharts');
jest.dontMock('.../HighCharts');
});
The downside is that dontMock
may not be executed if the import fails, so it can affect other tests, this needs to be additionally handled. It may be more straightforward to enforce default module state that is preferable for most tests:
beforeEach(() => {
jest.unmock('.../HighCharts');
jest.resetModules();
});