javascript - 如何使用 jest 模拟 react-router-dom 的 BrowserRouter

标签 javascript reactjs testing jestjs

我有这个呈现应用程序路由的组件:https://jsbin.com/bahaxudijo/edit?js ,我正在尝试模拟 BrowserRouter 和 Route 来进行测试,这是我的测试:

import React from 'react';
import renderer from 'react-test-renderer';

import Router from '../../../components/Router/Component';

jest.mock('react-router-dom', () => ({
  BrowserRouter: ({ children }) => <div>{children}</div>,
  Route: ({ children }) => <div>{children}</div>,
}));

jest.mock('../../../components/Nav/index', () => '<MockedNav />');
jest.mock('../../../components/ScheduleManager/index', () => '<MockedScheduleManager />');

const props = {
  token: '',
  loginStaff: jest.fn(),
};

describe('<Router />', () => {
  describe('When is passed a token', () => {
    it('renders the correct route', () => {
      const component = renderer.create(<Router {...props} />);
      expect(component).toMatchSnapshot();
    });
  });
});

但是我模拟错了 BrowserRouter 和 Route,所以测试通过了,但是快照只是空的 div。我怎样才能正确模拟 BrowserRouter 和路由?

最佳答案

jest.mock('react-router-dom', () => {
  // Require the original module to not be mocked...
  const originalModule = jest.requireActual('react-router-dom');

  return {
    __esModule: true,
    ...originalModule,
    // add your noops here
    useParams: jest.fn(),
    useHistory: jest.fn(),
  };
});

关于javascript - 如何使用 jest 模拟 react-router-dom 的 BrowserRouter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51031761/

相关文章:

javascript - 如何将原型(prototype)模式引入javascript命名空间

javascript - 如何为使用window.open打开的新窗口指定外部js和css

reactjs - 如何在youtube api上运行搜索查询,收到错误

go - 是否有众所周知的四元数测试向量?惩罚幼稚实现的已知测试代码?

c# - WPF 应用程序的测试自动化

javascript - 抛出错误 ('msg' ) vs 抛出新错误 ('msg' )

Javascript - 停止在某些链接上滚动

reactjs - React MUI 菜单不关闭

javascript - 使用数据数组 react native ListView

ruby - 测试 thor CLI 时禁用警告