【问题标题】:How to mock BrowserRouter of react-router-dom using jest如何使用 jest 模拟 react-router-dom 的 BrowserRouter
【发布时间】:2018-12-04 12:26:29
【问题描述】:

我有这个渲染应用程序路由的组件: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 和 Route?

【问题讨论】:

    标签: javascript reactjs testing jestjs


    【解决方案1】:

    另一种方式:

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

    来源:

    【讨论】:

      【解决方案2】:
      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(),
        };
      });
      

      【讨论】:

      • 不起作用,导致错误:jest.mock() is not allowed to reference any out-of-scope variables. Invalid variable access: jest - 指向 >>> const originalModule = jest.requireActual('react-router-dom');
      【解决方案3】:
      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;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-10
        • 2020-03-11
        • 1970-01-01
        • 1970-01-01
        • 2018-02-07
        • 2018-04-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多