Mocking React Router’s match object in component unit tests

Adam J. Arling
2 min readSep 24, 2019

Recently our UI team has switched from Enzyme to Kent Dodd’s Testing Library for a much improved, simplified experience in testing JavaScript and React components.

The issue
We have a growing number of applications which rely upon React Router to to handle client-side routing, and a good number of “container” components are dependent upon a URL parameter value for making network requests.

When testing these components with Testing Library / Jest, we need a way to mock routes and route parameter values via React Router’s match object in our component tests.

Setup
In one application, the following UI interface route is structured as http://some-url-here/project/project-id-goes-here:

A url parameter in current route

In a React container component which drives the UI above, the component’s network request is dependent upon the id from match.params (which is passed as a prop to the component when wrapped with React Router’s withRouter()).

So, the component grabs a project id value, then passes the value to our GraphQL API to retrieve additional project data for the component.

--

--

Adam J. Arling

Front End Developer who enjoys creating exceptional user experiences using JavaScript, React, TypeScript, NextJS, and API-driven development.