使用Enzyme测试包含React Router Link的组件

4

我正在使用enzyme。 我需要测试一个包含react router Link作为子元素的组件。 我需要执行以下操作:

  • 使用Enzyme的mount()来挂载组件,因为我需要测试整个组件树
  • 当组件属性改变时,测试其行为。

我不能使用StaticRouter或MemoryRouter包装我的组件,因为Enzyme只允许在根级别设置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"?
谢谢。

请查看我的回答,它可能会对你有所帮助。https://dev59.com/6FcP5IYBdhLWcg3w0tQ1#52533139 - 亚里士朱德
1个回答

1

不确定这是否对任何人有帮助,但对于我的情况,我通过浅渲染顶层组件,然后使用dive()方法来获取所需部分。

loginPage = shallow(<LoginPage />);

....

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接