【问题标题】:Jest reuse mock next/route object开玩笑重用模拟下一个/路由对象
【发布时间】: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


【解决方案1】:

试试这个:

在文件夹中创建一个文件mock:&lt;rootDir&gt;/jest/__mocks__/routerMock.js并添加mock

jest.mock('next/router', () => ({
  push: jest.fn(),
  back: jest.fn(),
  events: {
    on: jest.fn(),
    off: jest.fn(),
  },
  beforePopState: jest.fn(() => null),
  useRouter: () => ({
    push: jest.fn(),
  }),
}));

2 - 在jest.config.js 文件中,添加以下内容:

setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],

3 - 在jest.setup.js 文件中,导入routerMock.js

import './jest/__mocks__/routerMock';

4 - 测试您的组件

import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import Router from 'next/router'

 it('when the "next page" button is clicked', () => {
    render(<StuffComponent />);
    const button = screen.getByRole('button', { name: 'Next page' })

    userEvent.click(button)

    expect(Router.push).toHaveBeenCalledWith('/next-page');

 });

【讨论】:

    猜你喜欢
    • 2018-10-23
    • 2021-07-03
    • 2020-08-20
    • 2018-12-30
    • 2019-11-04
    • 1970-01-01
    • 2022-12-24
    • 2019-06-14
    • 2019-12-21
    相关资源
    最近更新 更多