我正在将我们的应用程序迁移到 react-router@4.x
,我在获取使用 enzyme
的测试时遇到了麻烦的 mount
功能。
每当我安装一个具有 withRouter
的组件时-wrapped 子组件,我遇到了麻烦。
这是我正在测试的简化情况的示例:
class SomePage extends React.Component {
componentDidMount() {
this.props.getData();
}
render() {
return (
<div>
<ComponentWrappedInWithRouter />
</div>
);
}
}
const Component = (props) => (
<button onClick={() => this.props.history.push('/new-route') }>
Click to navigate
</button>
);
const ComponentWrappedInWithRouter = withRouter(Component);
现在,我想测试一下 SomePage
调用它的 Prop getData
安装后。愚蠢的例子,我知道,但结构应该足够了。
每当我编写使用 enzyme
的测试时的 mount
,我收到以下错误:
TypeError: Cannot read property 'route' of undefined
at Route.computeMatch (node_modules/react-router/Route.js:68:22)
at new Route (node_modules/react-router/Route.js:47:20)
现在,我认为发生这种情况的原因是因为我尝试调用 withRouter
对于没有 router
的组件在上下文中 - 即它没有被包装在 <BrowserRouter />
中或其 sibling 之一。
这不是 react-router@3.x
的问题, 但由于当前的专业是完全重写的,所以我完全理解会出现这些问题。
关于如何解决这个问题有什么想法吗?
最佳答案
非常简单:将您正在测试的组件包装在 react-router-dom
的 MemoryRouter
中,您就可以开始了。
关于reactjs - 使用 react-router v4 测试安装的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44804268/