Skip to content Skip to sidebar Skip to footer

How To Mock Module In Different Ways In Different Tests In The Same Test File In Jest?

Currently I have this: jest.mock('my/hook', () => () => false) I want my custom React hook module to return false in every test by default, but in a few tests I want it to r

Solution 1:

jest.doMock alone can't do anything because a module that depends on it has been already imported earlier. It should be re-imported after that, with module cache discarded with either jest.resetModules or jest.isolateModules:

beforeEach(() => {
  jest.resetModules();
});

it('should do x', () => {
  jest.doMock('my/hook', ...)
  require('module that depends on hook');
  // ... rest of test
})

Since it's a function that needs to be mocked differently, a better way is to mock the implementation with Jest spies instead of plain functions:

jest.mock('my/hook', () => jest.fn(() =>false))
...
it('should do x', () => {
  hook.mockReturnValueOnce(true);
  // ... rest of test
})

Post a Comment for "How To Mock Module In Different Ways In Different Tests In The Same Test File In Jest?"