【发布时间】:2017-06-28 13:43:44
【问题描述】:
我正在将我们的应用程序迁移到 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)
现在,我认为发生这种情况的原因是因为我尝试为上下文中没有 router 的组件调用 withRouter - 即它没有被包裹在 <BrowserRouter /> 或其兄弟姐妹中。
这不是react-router@3.x 的问题,但是由于当前的专业是完全重写的,我完全理解这些问题会出现。
关于如何解决此问题的任何想法?
【问题讨论】:
标签: reactjs testing react-router enzyme