跨测试重用 Jest 模块模拟

时间:2021-06-10 15:25:44

标签: jestjs mocking next.js es6-modules

我想模拟一个模块进行测试。一切正常,但我必须将相同的代码复制/粘贴到每个测试文件中。我怎样才能使它更易于维护?

(这是在 Next.js 项目中使用 Babel 和 TypeScript。)

生产代码如下所示:

import { useRouter } from 'next/router';

// Then call the hook in a React component:
  const router = useRouter();

测试代码:

// I need to access these mocks in the tests
const mockRouterPush = jest.fn();
const mockRouterBack = jest.fn();

jest.mock('next/router', () => ({
  useRouter: () => ({
    push: mockRouterPush,
    query: { segment: 'seg1' },
    back: mockRouterBack,
  }),
}));

这很好用。该模块及其钩子是针对测试文件进行模拟的,我可以参考测试中的模拟。问题是很难跨多个测试文件进行维护。

jest.mock() 的调用被提升到文件的顶部,并且只能引用以单词 'mock' 开头的变量。

对于其他模拟,我在模块工厂中使用了 require 而不是 import;这有效并减少了样板文件,但是 (a) 使测试更难以引用模拟,并且 (b) 我的 IDE (VSCode) 不会像在移动文件时那样自动更新需要路径。例如:

jest.mock('react-i18next', () => {
  // Sometimes the path is '../../../testhelpers' etc.
  const { mockUseTranslation } = require('./testhelpers');

  return {
    useTranslation: mockUseTranslation,
  };
});

我试过 doMockcreateMockFromModule 都没有成功。

其他人如何处理这个问题?

1 个答案:

答案 0 :(得分:2)

也许使用 __mock__ 目录可以帮助您。

来自文档:

<块引用>

手动模拟是通过在紧邻模块的 mocks/ 子目录中编写一个模块来定义的。例如,要模拟models 目录中名为user 的模块,请创建一个名为user.js 的文件并将其放在models/mocks 目录中。

您还可以模拟 node_modules 目录中的模块。

Manual Mocks