代码之家  ›  专栏  ›  技术社区  ›  Liz Parody

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

  •  4
  • Liz Parody  · 技术社区  · 7 年前

    我有一个呈现应用程序路由的组件: https://jsbin.com/bahaxudijo/edit?js

    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和路由,所以测试通过了,但是快照只是空div。我怎样才能正确地模拟浏览器路由器和路由?

    1 回复  |  直到 7 年前
        1
  •  6
  •   curtybear    5 年前
    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(),
      };
    });
    
        2
  •  1
  •   Jeff    6 年前
    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;
    
        3
  •  1
  •   Lucio    5 年前

    另一种方式:

    const rrd = require('react-router-dom');
    
    jest.spyOn(rrd, 'BrowserRouter').mockImplementation(({children}) => children);
    

    资料来源: