简体   繁体   English

如何覆盖 setupFiles (jest.config.js) 中定义的 jest.mock

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

In jest.config.js:在 jest.config.js 中:

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

In jest.init.js:在 jest.init.js 中:

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

So in all tests that import isMobile from 'xxx/layout' isMobile will be false所以在所有从 'xxx/layout' isMobile 导入 isMobile 的测试中都是错误的

Now i tried to override isMobile in some tests like so:现在我试图在一些测试中重写 isMobile,如下所示:

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.安装文件在 Jest 设置测试环境时运行。 You can see the sequence of the job like below:您可以看到作业的顺序,如下所示:

  1. Jest runs jest.init.js , mocks xxx/layout ; Jest 运行jest.init.js ,模拟xxx/layout
  2. Jest runs individual test file, and if you import your module before your override is run, it will not update dynamically Jest 运行单独的测试文件,如果您在覆盖运行之前导入模块,它将不会动态更新

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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