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

seb*_*bap 8 reactjs jestjs

在 jest.config.js 中:

setupFiles: ['<rootDir>/jest.init.js'],
Run Code Online (Sandbox Code Playgroud)

在 jest.init.js 中:

jest.mock('xxx/layout', () => ({
  ...
  isMobile: false,
  ...
}))
Run Code Online (Sandbox Code Playgroud)

因此,在从 'xxx/layout' 导入 isMobile 的所有测试中,isMobile 将为 false

现在我尝试在一些测试中覆盖 isMobile,如下所示:

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

isMobile.mockImplementation(() => true)
Run Code Online (Sandbox Code Playgroud)

但这不起作用!

这样做的好方法是什么?

tro*_*ish 5

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

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

Run Code Online (Sandbox Code Playgroud)

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

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