【问题标题】:Testing react-router v4 with Jest and Enzyme使用 Jest 和 Enzyme 测试 react-router v4
【发布时间】:2017-11-10 12:44:13
【问题描述】:

我有一个他们使用 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);
  });
});

为什么这个测试失败了?

我的配置:

  • 酶:2.8.2
  • 反应脚本:1.0.7
  • 反应测试渲染器:15.5.4

【问题讨论】:

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


    【解决方案1】:

    您必须提供initialEntriesinitialIndex。 在您的情况下,它应该如下所示:

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

    另一种可能是您需要enzymemount 而不是shallow

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

    【讨论】:

    • 如果我将contains 替换为equals,如何更改此测试?
    • 有一个 github.com/blainekasten/enzyme-matchers 库,它允许您编写类似:expect(wrapper.find(Component)).toBePresent() 的内容。但是您可能不需要额外的库。查看官方enzyme 文档,其中对可用选择器有很好的解释。在你的情况下,像expect(wrapper.find(&lt;div&gt;Home&lt;/div&gt;)).toHaveLength(1) 这样的东西可以工作。
    • 我正在这样做,但问题是他们的孩子是 memoryRouter(在 Mount 时),你不能 setState 等等
    猜你喜欢
    • 1970-01-01
    • 2017-11-26
    • 2019-02-20
    • 2020-08-07
    • 2018-02-25
    • 2019-06-26
    • 2019-01-27
    • 2018-07-11
    相关资源
    最近更新 更多