简体   繁体   中英

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? 在此处输入图片说明

My config:

  • enzyme: 2.8.2
  • react-scripts: 1.0.7
  • react-test-renderer: 15.5.4

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM