Categories
React Answers

How to test components using React Router hooks with Jest?

Spread the love

Sometimes, we want to test components using React Router hooks with Jest.

In this article, we’ll look at how to test components using React Router hooks with Jest.

How to test components using React Router hooks with Jest?

To test components using React Router hooks with Jest, we can mock individual hooks in the react-router-dom module with jest.mock.

For instance, we write

jest.mock("react-router-dom", () => ({
  ...jest.requireActual("react-router-dom"),
  useParams: () => ({
    companyId: "company-id1",
    teamId: "team-id1",
  }),
  useRouteMatch: () => ({ url: "/company/company-id1/team/team-id1" }),
}));

to call jest.mock to mock the react-router-dom module.

We call jest.requireActual to put the actual module in the object we return in the mock callback.

And then override the hooks’ values with the mocked ones.

We set useParams to a function that returns the values we want in the component being tested.

And we do the same with useRouteMatch.

Conclusion

To test components using React Router hooks with Jest, we can mock individual hooks in the react-router-dom module with jest.mock.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *