简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM