Difference between jest.mock and jest.doMock

11,745

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();
});
Share:
11,745
Chrissi Grilus
Author by

Chrissi Grilus

Updated on June 11, 2022

Comments

  • Chrissi Grilus
    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
    Estus Flask about 3 years
    Jest tries to push jest.mock above relevant import. It doesn't do this for doMock. That's the difference.