sebap
sebap

Reputation: 1691

How to override jest.mock defined in a setupFiles (jest.config.js)

In jest.config.js:

setupFiles: ['<rootDir>/jest.init.js'],

In jest.init.js :

jest.mock('xxx/layout', () => ({
  ...
  isMobile: false,
  ...
}))

So in all tests that import isMobile from 'xxx/layout' isMobile will be false

Now i tried to override isMobile in some tests like so:

jest.mock('xxx/layout', () => ({ isMobile: true }))

isMobile.mockImplementation(() => true)

But it's not working!

What would be the good way to do it?

Upvotes: 9

Views: 4038

Answers (1)

tropicalfish
tropicalfish

Reputation: 1270

You must reimport the module again after your second mock: In your test file:

test('Test', () => {
  jest.mock('xxx/layout', () => ({ isMobile: true }))
  const layout = require('xxx/layout'); // require the new mock
  // run your test here
});

The setup file is run when Jest is setting up your testing environment. You can see the sequence of the job like below:

  1. Jest runs jest.init.js, mocks xxx/layout;
  2. Jest runs individual test file, and if you import your module before your override is run, it will not update dynamically

Upvotes: 7

Related Questions