我有一个React组件,它包含在高阶组件withRouter中,如下所示:
module.exports = withRouter(ManageProfilePage);
我的路线如下:
<Route path="/" component={AdrApp}>
<IndexRoute component={Login}/>
<Route component={CheckLoginStatus}>
<Route path="manage-profiles/:profileId" component=
{ManageProfilesPage}/>
</Route>
<Route path="*" component={notFoundPage}/>
</Route>
我需要使用一次Router生命周期方法,这就是我需要withRouter的原因:
class ManageProfilePage extends React.Component {
componentDidMount() {
this.props.router.setRouteLeaveHook(this.props.route, () => {
...
})
render(){
...
}
}
我需要使用Jest / Enzyme测试这个组件,我编写了如下测试用例:
describe('manage profile page test suite', () => {
it('snapshot test', () => {
const setRouteLeaveHook =jest.fn();
let wrapper = shallow(
<ManageProfilePage params={{id : 25, router:
setRouteLeaveHook}}/>
);
expect(wrapper).toMatchSnapshot();
})
})
问题是它没有渲染一个级别。我正在粘贴下面的快照:
exports[`manage drug term page test suites snapshot test 1`] = `
<ManageProfilePage
params={
Object {
"id": 25,
"router": [Function],
}
}
/>
`;
我可以用不同的方式编写测试用例,以便能够将ManageProfilePage渲染至少1级吗?因为它被包含在WithRouter中而无法呈现?我们如何测试这些类型的组件?
答案 0 :(得分:25)
通常,如果我们尝试测试这些组件,我们将无法呈现它,因为它被包装在WithRouter中(WithRouter是一个包含在组件上的包装器) 路由器道具,如匹配,路由和历史记录,可直接在组件中使用)。 module.exports = withRouter(ManageProfilePage);
要渲染此类组件,我们必须明确告诉它使用WrappedComponent关键字渲染包装组件。 对于Eg。我们将使用以下代码进行快照测试:
describe('manage profile page test suite', () => {
it('snapshot test', () => {
const setRouteLeaveHook =jest.fn();
let wrapper = shallow(
<ManageProfilePage.WrappedComponent params={{id : 25, router:
setRouteLeaveHook}}/>
);
expect(wrapper).toMatchSnapshot();
})
})
这将告诉酶为ManageProfilePage进行浅层渲染(Shallow Rendering仅渲染该特定组件并跳过子组件),这是WithRouter中的包装组件。
答案 1 :(得分:1)
浅层渲染只会渲染一个级别,这是规范的一部分。
你可以使用Mount来渲染整个树,但我认为你不能限制它渲染的深度级别。
在任何情况下,当使用高阶组件时,我通常也会导出基本组件(在包装之前),这样我就可以在没有包装器的情况下完成所有测试,只需为所需的提供程序传递模拟。
与使用redux的Connect
组件相同,您导出常规组件并测试其上的不同道具,而不是连接的道具。
还要注意,有些with...
包装器不公开内部实例(有些没有,但有些没有),所以测试你自己的组件而不是包装器也有帮助。
答案 2 :(得分:0)
我认为您应该尝试这个
describe('manage profile page test suite', () => {
it('snapshot test', () => {
let wrapper = shallow(
<ManageProfilePage.WrappedComponent/>
);
expect(wrapper).toMatchSnapshot();
})
})
答案 3 :(得分:-1)
我做了什么解决了这个问题:
在“this.props.match.params.id”中使用了post组件
在测试用例中
const miniProps = { otherProps, match:{params:{id:'112'}} }; const wrapper = shallow();