[英]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:
您可以看到作业的顺序,如下所示:
jest.init.js
, mocks xxx/layout
; jest.init.js
,模拟xxx/layout
;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.