Using Jest to test a Link from react-router v4

Don P picture Don P · May 4, 2017 · Viewed 25.1k times · Source

I'm using jest to test a component with a <Link> from react-router v4.

I get a warning that <Link /> requires the context from a react-router <Router /> component.

How can I mock or provide a router context in my test? (Basically how do I resolve this warning?)

Link.test.js

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

test('Link matches snapshot', () => {
  const component = renderer.create(
    <Link to="#" />
  );

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

The warning when the test is run:

Warning: Failed context type: The context `router` is marked 
as required in `Link`, but its value is `undefined`.

Answer

Andreas K&#246;berle picture Andreas Köberle · May 4, 2017

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