Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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. How can I properly mock the BrowserRouter and the Route?

like image 794
Liz Parody Avatar asked Jun 25 '18 21:06

Liz Parody


3 Answers

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(),
  };
});
like image 68
curtybear Avatar answered Sep 19 '22 12:09

curtybear


Yet another way:

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

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

Sources:

  • https://medium.com/@antonybudianto/react-router-testing-with-jest-and-enzyme-17294fefd303
  • https://stackoverflow.com/a/56565849/1505348
like image 29
Lucio Avatar answered Sep 19 '22 12:09

Lucio


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;
like image 40
Jeff Avatar answered Sep 19 '22 12:09

Jeff