使用Jest和Enzyme测试react-router v4

Pav*_*vel 11 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>
);
Run Code Online (Sandbox Code Playgroud)

并测试

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);
  });
});
Run Code Online (Sandbox Code Playgroud)

为什么这个测试会下降 在此输入图像描述

我的配置:

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

Tom*_*ski 9

你必须提供initialEntries以及initialIndex.在你的情况下,它应该是这样的:

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

另一种可能性是,你需要enzymemount不是shallow.

react-router这里有一些很棒的文档:https: //reacttraining.com/react-router/core/api/MemoryRouter