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

8
在 jest.config.js 文件中:
setupFiles: ['<rootDir>/jest.init.js'],

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

因此,在所有导入“xxx/layout”中的isMobile的测试中,isMobile都将为false。

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

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

isMobile.mockImplementation(() => true)

但是它没有起作用!

有什么好的方法来解决这个问题呢?

1个回答

5

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

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运行单独的测试文件,如果在重写运行之前导入了您的模块,它将不会动态更新。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接