Difference between jest.mock and jest.doMock
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();
});
![Chrissi Grilus](https://lh5.googleusercontent.com/-b7jbTSQMPSQ/AAAAAAAAAAI/AAAAAAAAAAA/ACHi3repZONg5p-G3pNTXaUlvhow8HG9EQ/mo/photo.jpg?sz=256)
Chrissi Grilus
Updated on June 11, 2022Comments
-
Chrissi Grilus about 2 years
I want this to be specific to a single test:
it('should mock the module a single time', () => { jest.doMock('../../../../../../../components/HighCharts/HighCharts', () => { return () => <div id="mock-line-chart" />; }); })
but it doesnt work. This works for the whole file:
jest.mock('../../../../../../../components/HighCharts/HighCharts', () => { return () => <div id="my-special-div" />; });
Am I not using this right? Where is the difference between doMock and mock. I it suitable to do a module mock for a single test only?
-
Estus Flask about 3 yearsJest tries to push jest.mock above relevant import. It doesn't do this for doMock. That's the difference.