【问题标题】:Testing components that contain react router Link with Enzyme测试包含 react router Link with Enzyme 的组件
【发布时间】:2018-03-12 23:36:02
【问题描述】:

我正在使用酶。我需要测试一个组件,该组件具有反应路由器链接作为一个孩子。我需要以下内容

  • 使用酶的 mount() 安装组件,因为我需要测试整个组件树
  • 测试组件属性变化时的行为。

我不能用 StaticRouter 或 MemoryRouter 包装我的组件,因为酶只允许在根级别设置 setProps()。

我目前的解决方案是使用 sinon 存根 Link 渲染方法。这是一个简短的例子。

import {Link} from 'react-router-dom';
import sinon from 'sinon';

// ....
// ....

describe('test',() => {
   before(() => {
      sinon.stub(Link.prototype, 'render').callsFake(function reactRouterLinkRender() {
           const {innerRef, replace, to } = this.props;
           const _props = {href: to, ref: innerRef, replace, onClick: this.handleClick};
           return (<a {..._props}>this.props.children</a>);
       });

    });
});

有没有更好的方法来避免错误“Invariant Violation: You should not use Link outside a Router”?

谢谢

【问题讨论】:

标签: reactjs enzyme


【解决方案1】:

不确定这是否对任何人有帮助,但就我而言,我设法通过浅层渲染顶级组件然后使用dive() 来获得我需要的部分。

loginPage = shallow(<LoginPage />);

....

loginPage.find(LoginForm).dive().find({name:"user"}).simulate("change", userEventMock);

【讨论】:

    猜你喜欢
    • 2018-07-11
    • 1970-01-01
    • 1970-01-01
    • 2017-11-26
    • 2020-01-23
    • 2019-03-10
    • 2018-05-26
    • 2017-02-12
    • 2017-11-10
    相关资源
    最近更新 更多