使用Jest和Enzyme

时间:2017-06-08 17:10:30

标签: javascript reactjs jestjs enzyme react-router-v4

我有一个简单的应用程序,他们使用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>
);

并测试

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

为什么这个测试会下降? enter image description here

我的配置:

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

1 个答案:

答案 0 :(得分:9)

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