How to test components using new react router hooks?

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.

Leave a Comment