Using Jest to test a Link from react-router v4

You can wrap your component in the test with the StaticRouter to get the router context into your component:

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>
  );

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

Have a look at the react router docs about testing

Leave a Comment