gpt4 book ai didi

reactjs - 测试 withRouter 中包含的 react 组件(最好使用 jest/enzyme)

转载 作者:行者123 更新时间:2023-12-03 13:01:55 26 4
gpt4 key购买 nike

我有一个 React 组件,它包含在带有 Router 的高阶组件中,如下所示:

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 中?我们如何测试这些类型的组件?

最佳答案

通常,如果我们尝试测试此类组件,我们将无法渲染它,因为它被包装在 WithRouter 中(WithRouter 是一个组件的包装器,它提供路由器属性(如匹配、路由和历史记录)可在组件中直接使用。module.exports = withRouter(ManageProfilePage);

要渲染此类组件,我们必须显式地告诉它使用 WrappedComponent 关键字渲染包装的组件。对于例如。我们将使用以下代码进行快照测试:

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();
})
})

这将告诉 enzyme 为 ManageProfilePage 进行浅层渲染(浅层渲染仅渲染该特定组件并跳过子组件),该组件被包装在 WithRouter 中。

关于reactjs - 测试 withRouter 中包含的 react 组件(最好使用 jest/enzyme),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44204828/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com