0

Using React Router DOM (v6) with React Testing Library, I would like to know if there's a way to deal with "mocked" history from createMemoryHistoryor an alternative like it.

Based on the example of Testing Library, I could mock the history on the Router component but in v6 this component doesn't accept the history prop anymore.

So, my doubt is: how can I test history and location with RTL (React Testing Library) with React Router DOM v6? Should I keep using the MemoryRouter?

Doskya
  • 1
  • 1
  • RRDv6 rather tucks away and internalizes its own history reference, so it's not directly exposed via any of the higher level routers. You can create your own custom router to use a custom history object. – Drew Reese Dec 11 '21 at 08:38
  • Yep! As I saw in the codebase, apparently they don't have any way to access the history reference on the `Routers`. So I think that I need to write a custom router to deal with history object as you say. Thank you for the help! – Doskya Dec 12 '21 at 16:11
  • You may find this [answer](https://stackoverflow.com/a/70000286/8690857) helpful/useful. Cheers. – Drew Reese Dec 12 '21 at 18:53

1 Answers1

0

Using react router dom v6, Router use navigator prop to accept history.

const history = createMemoryHistory(); 
...
<MockedProvider mocks={[]}>
  <Router navigator={history} location={"/"}>
    <Home />
  </Router>
</MockedProvider> 
... 
await waitFor(() => {
  expect(history.location.pathname).toBe("/");
});
Jur P
  • 85
  • 6