【发布时间】:2020-05-17 04:32:59
【问题描述】:
我有这样的模拟:
jest.mock('next/router', () => ({
push: jest.fn(),
events: {
on: jest.fn(),
off: jest.fn()
},
beforePopState: jest.fn(() => null)
}));
我需要在我想要重复使用它的地方使用它。我尝试什么,
我创建了文件夹 __mocks__ 和文件 mock.js。
mock.js:
export default () => jest.mock('next/router', () => ({
push: jest.fn(),
events: {
on: jest.fn(),
off: jest.fn()
},
beforePopState: jest.fn(() => null)
}));
在我的 component.test.js 中导入模拟。 组件.test.js:
import '../__mocks__/mocks';
但是当我渲染组件时出现错误:
it('should mount and sub to "routerChangeStart"', async () => {
render(<LoseChangesWarning dirty isSubmitting={false} />);
await wait(() => {
expect(Router.events.on).toHaveBeenCalledTimes(1);
expect(Router.beforePopState).toHaveBeenCalled();
});
错误信息: 找不到路由器实例。 您应该只在应用的客户端内使用“next/router”。
【问题讨论】:
标签: reactjs unit-testing jestjs next.js