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