Testing React Router apps with Jest and Enzyme

Antony Budianto
Aug 11, 2017 · 2 min read

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!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store