[React] Unit Testing with React Router

When writing unit tests, different people have different ideas on how to assert against whether navigating to a different page was successful or not.

Let’s say I have a main page that can navigate to a secondary page. In order to navigate, the implementation needs to use useNavigate from react-router-dom.

Here is what MainPage looks like:

My preferred way of writing a unit test for MainPage to navigate to a different page is:

Note that this approach works with React Router v5 with useHistory as well.




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