Difference between MemoryRouter and Router concerning testing with react-testing-library
Asked Answered
T

1

7

I work on a small App to get familiar with testing and such in React, using jest and React-Testing-Library.

In my <App /> Component, I have a Routes with two Route. One of those looks like this:

<Route path='/' element={<RequireAuth><Dashboard /></RequireAuth>} />

If the user is not logged in, <RequireAuth /> redirects the user to a Login /> Component via <Navigate to="/login" />.

This is just for context. All of this works. But for quite some time, I couldnt make the test pass to check that the Navigation happens. I figured, that my problem was the Route method I used in React-Testing-Librariesrender() method. The test passes if I use <MemoryRouter /> but doesnt if I wrap <App /> in <Router location={history.location} navigator={history} />..

In the following stackblitz, I have implemented both versions. The one that s not working, is currently commented out. Could someone tell me, why it only works with MemoryRouter? You find the test in src/routing.test.tsx. You can run the tests with npm run test. https://stackblitz.com/edit/github-nfj4lw?file=src/routes.test.tsx

Tatiana answered 29/1, 2022 at 11:3 Comment(0)
A
7

The Router is a low level function that is not environment specific. As the docs state, you probably never want to render your components with it. Replacing it with higher level environment aware functions like BrowserRouter or (MemoryRouter) makes your test pass:

// routes.test.tsx
import { BrowserRouter } from 'react-router-dom';
it('Testing if Route Login gets rendered by default', () => {
  render(
    
    <BrowserRouter>
      <Provider store={store}>
        <App />
      </Provider>
    </BrowserRouter>
  );

  expect(
    screen.getByText('Welcome to nutri. Please Login.')
  ).toBeInTheDocument();
});

If you want something more, you can add further assertions by querying the location/history stack.

Note: using MemoryRouter in tests is preferred to BrowserRouter since it allows you to keep your routing history independent of any external source. React-router uses it in many of its tests.

Amman answered 29/1, 2022 at 11:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.