使用 react-router v4 测试安装的组件
Testing mounted components with react-router v4
我正在将我们的应用程序迁移到 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
的问题,但由于当前专业是完全重写的,我完全理解这些问题将会出现。
关于如何解决这个问题有什么想法吗?
非常简单:将您正在测试的组件包装在 react-router-dom
的 MemoryRouter
中,您就可以开始了。
我正在将我们的应用程序迁移到 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
的问题,但由于当前专业是完全重写的,我完全理解这些问题将会出现。
关于如何解决这个问题有什么想法吗?
非常简单:将您正在测试的组件包装在 react-router-dom
的 MemoryRouter
中,您就可以开始了。