Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test components using new react router hooks?

Tags:

react-router

Until now, in unit tests, react router match params were retrieved as props of component. So testing a component considering some specific match, with specific url parameters, was easy : we just had to precise router match's props as we want when rendering the component in test (I'm using enzyme library for this purpose).

I really enjoy new hooks for retrieving routing stuff, but I didn't find examples about how to simulate a react router match in unit testing, with new react router hooks ?

like image 563
Remi Deprez Avatar asked Sep 26 '19 13:09

Remi Deprez


People also ask

How do you test a custom react hook?

1st case: unit testing simple custom hooks First, we need to create a test using describe. Then, we render a hook to use it for testing. Common way of doing it is to use the renderHook method from the React Hooks Testing Library. The next step is to figure out which cases we need to check.

Why useHistory is used in react?

useHistory: This is one of the most popular hooks provided by React Router. It lets you access the history instance used by React Router. Using the history instance you can redirect users to another page.


1 Answers

Edit: The proper way of doing this the way described in Catalina Astengo's answer as it uses the real router functionality with just the history/routing state mocked rather than mocking the entire hook.

The way I ended up solving it was by mocking the hooks in my tests using jest.mock:

// TeamPage.test.js jest.mock('react-router-dom', () => ({   ...jest.requireActual('react-router-dom'), // use actual for all non-hook parts   useParams: () => ({     companyId: 'company-id1',     teamId: 'team-id1',   }),   useRouteMatch: () => ({ url: '/company/company-id1/team/team-id1' }), })); 

I use jest.requireActual to use the real parts of react-router-dom for everything except the hooks I'm interested in mocking.

like image 194
Markus-ipse Avatar answered Sep 23 '22 18:09

Markus-ipse