【发布时间】: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”?
谢谢
【问题讨论】:
-
请看我的回答。它可以帮助你。 stackoverflow.com/a/52533139/5465023