繁体   English   中英

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

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

在 jest.config.js 中:

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

在 jest.init.js 中:

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

所以在所有从 'xxx/layout' isMobile 导入 isMobile 的测试中都是错误的

现在我试图在一些测试中重写 isMobile,如下所示:

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

isMobile.mockImplementation(() => true)

但它不起作用!

这样做的好方法是什么?

您必须在第二次模拟后再次重新导入模块:在您的测试文件中:

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

安装文件在 Jest 设置测试环境时运行。 您可以看到作业的顺序,如下所示:

  1. Jest 运行jest.init.js ,模拟xxx/layout
  2. Jest 运行单独的测试文件,如果您在覆盖运行之前导入模块,它将不会动态更新

暂无
暂无

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

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