Categories
React Answers

How to use Jest to test a Link from React Router v4?

Spread the love

Sometimes, we want to use Jest to test a Link from React Router v4.

In this article, we’ll look at how to use Jest to test a Link from React Router v4.

How to use Jest to test a Link from React Router v4?

To use Jest to test a Link from React Router v4, we can wrap our component with StaticRouter before we mount it.

For instance, we write

import React from "react";
import renderer from "react-test-renderer";
import { Link } from "react-router-dom";
import { StaticRouter } from "react-router";

test("Link matches snapshot", () => {
  const component = renderer.create(
    <StaticRouter location="someLocation" context={context}>
      <Link to="#" />
    </StaticRouter>
  );

  const tree = component.toJSON();
  expect(tree).toMatchSnapshot();
});

to wrap Link with StaticRouter before we call rendered.create.

Then we call component.toJSON to return the snapshot data.

And then we call expect and toMatchSnapshot` to check what’s rendered.

Conclusion

To use Jest to test a Link from React Router v4, we can wrap our component with StaticRouter before we mount it.

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 *