简体   繁体   English

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

[英]How to mock BrowserRouter of react-router-dom using jest

I have this components that renders the routes of an app: https://jsbin.com/bahaxudijo/edit?js , I'm trying to mock the BrowserRouter and the Route to do the test, this are my test:我有这个呈现应用程序路由的组件: 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();
    });
  });
});

But I'm mocking wrong the BrowserRouter and the Route, so the test passes but the snapshots are only empty divs.但是我在嘲笑 BrowserRouter 和 Route 是错误的,所以测试通过了,但快照只是空的 div。 How can I properly mock the BrowserRouter and the Route?如何正确模拟 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(),
  };
});
const reactRouter = require('react-router-dom'); const { MemoryRouter } = reactRouter; const MockBrowserRouter = ({ children }) => ( <MemoryRouter initialEntries={['/']}> { children } </MemoryRouter> ); MockBrowserRouter.propTypes = { children: PropTypes.node.isRequired }; reactRouter.BrowserRouter = MockBrowserRouter;

Yet another way:还有一种方式:

const rrd = require('react-router-dom');

jest.spyOn(rrd, 'BrowserRouter').mockImplementation(({children}) => children);

Sources:资料来源:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM