'how to implement page navigation in react testing library (Link, a tag, history.push)

I am trying perform Dom testing at '/test' url page.

my application use BrowseRouter from react-router-dom

As following user approach, I want to manually change page to '/test' using <Link /> from react-router-dom, but It doesn't work. I couldn't access page '/test'.

const App = () => {
 return (
    <BrowseRouter>
      <Route key="test" path="/test" component={TestPage} />
      <Route key="index" path="/" component={IndexPage} />
    </BrowseRouter>
 )
}
describe(() => {
  it("test TestPage", async () => {
    const history = createMemoryHistory()
    const { queryByTestId } = await waitFor(() => render(
      <Router history={history}>
       <App />
      </Router>
    ))
    userEvent.click(queryByTestId('#to_test_page')) // <Link /> to '/test'
    // history.location.pathname is still '/'
    // window.location.pathname is still '/'
  })
})

As a workaround, I had to wrap my routes with 'MemoryRouter', not a BrowseRouter, help setting entry url to '/test'. But It's not perfect approach for me.



Solution 1:[1]

Try awaiting the click

await act(async () => userEvent.click(queryByTestId('#to_test_page')));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 richardec