Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing react-router v4 with Jest and Enzyme

I have a simple app they use react-router v4

const App = () => (
  <Switch>
    <Route exact path="/" component={() => <div>Home</div>}/>
    <Route path="/profile" component={() => <div>Profile</div>}/>
    <Route path="/help" component={() => <div>Help</div>}/>
  </Switch>
);

and test

jest.dontMock('../App');

import React from 'react';
import { MemoryRouter } from 'react-router-dom';
import { shallow } from 'enzyme';

import App from '../App';

describe('<App />', () => {
  const wrapper = shallow(
    <MemoryRouter>
      <App/>
    </MemoryRouter>
  );

  console.log(wrapper.html());

  it('renders a static text', () => {
    expect(
      wrapper.contains(<div>Home</div>)
    ).toBe(true);
  });
});

Why does this test fail? enter image description here

My config:

  • enzyme: 2.8.2
  • react-scripts: 1.0.7
  • react-test-renderer: 15.5.4
like image 368
Pavel Avatar asked Jun 08 '17 17:06

Pavel


People also ask

How do I test my router push with Jest react?

import { useRouter } from "next/router"; jest. mock("next/router", () => ({ useRouter: jest. fn(), })); And then use like this inside your test block.

How do I test my router Jest?

You can use the createMemoryHistory function and Router component to test it. Create a memory history with initial entries to simulate the current location, this way we don't rely on the real browser environment. After firing the click event, assert the pathname is changed correctly or not.

How do you test for Jest and enzymes?

Both Jest and Enzyme are meant to test the react applications. Jest can be used with any other Javascript framework, but Enzyme is meant to run on react only. Jest can be used without Enzyme, and snapshots can be created and tested perfectly fine. But the Enzyme adds additional functionality to it.


1 Answers

You have to provide initialEntries as well as initialIndex. In your case it should look like this:

const wrapper = shallow(
  <MemoryRouter initialEntries={['/']} initialIndex={0}>
    <App/>
  </MemoryRouter>
);

Other possibility is that you need enzyme's mount instead of shallow.

react-router has some great documentation here: https://reacttraining.com/react-router/core/api/MemoryRouter

like image 125
Tomasz Cichociński Avatar answered Oct 20 '22 00:10

Tomasz Cichociński