【发布时间】:2021-08-27 15:21:00
【问题描述】:
我想模拟一个模块进行测试。一切正常,但我必须将相同的代码复制/粘贴到每个测试文件中。我怎样才能使它更易于维护?
(这是在 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,
};
});
我试过doMock 和createMockFromModule 都没有成功。
其他人如何处理这个问题?
【问题讨论】:
标签: jestjs mocking next.js es6-modules