Testing React Router apps with Jest and Enzyme

Antony Budianto
2 min readAug 11, 2017

--

I would like to share with you on how I test my React application that used React Router.

Test case:

Suppose you have following route configuration on App.js:

I would like to test that if I visit some random unknown path, then my App should render NotFoundPage component, or else, it should render the correct component.

So you can make the app to go to specific route by using MemoryRouter provided by react-router.

We also need to check the deep rendered component by the router so we must use mount() from enzyme.

test('invalid path should redirect to 404', () => {  const wrapper = mount(    <MemoryRouter initialEntries={[ '/random' ]}>      <App/>    </MemoryRouter>  );  expect(wrapper.find(LandingPage)).toHaveLength(0);  expect(wrapper.find(NotFoundPage)).toHaveLength(1);});

MemoryRouter have initialEntries prop to custom your initial route path.

Don’t forget to mock the BrowserRouter used by App.js by creating __mocks__/react-router-dom.js and here is how to mock it:

import React from 'react';const rrd = require('react-router-dom');// Just render plain div with its children
rrd.BrowserRouter = ({children}) => <div>{children}</div>
module.exports = rrd;

We need to mock it because it’ll overlap with our MemoryRouter and causing the initialEntries not working.

Now try to run your test by running npm test and it should pass correctly.

Here is my full test:

You can check the repo here too. (coming soon)

Stack used:

  • Create React App
  • React Router 4.1.2
  • Jest
  • Enzyme

If you have any questions or suggestions, feel free to ask.

Thank you for reading!

P.S. I just started my new YouTube channel, and I’ve posted “Learn React testing in 2 minutes”, please watch, like, share, and subscribe!

--

--

Antony Budianto

Not active on medium anymore. Follow me on twitter @antonybudianto