小编典典

测试随路由器附带的反应组件(最好使用笑话/酶)

reactjs

我有一个React组件,它包含在带有路由器的高级组件中,如下所示:

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>

我需要使用一次路由器生命周期方法,这就是为什么需要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],
    }
  }
/>
`;

有什么其他方法可以编写我的测试用例,从而使我能够至少渲染1层ManageProfilePage?它无法呈现,因为它包含在WithRouter中?我们如何测试这些类型的组件?


阅读 261

收藏
2020-07-22

共1个答案

小编典典

通常,如果我们尝试测试此类组件,我们将无法对其进行渲染,因为它被包装在WithRouter中(WithRouter是组件的包装器,提供了诸如匹配,路由和历史记录之类的Router道具,可在该组件中直接使用)。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();
    })
   })

这将告诉酵素为ManageProfilePage进行浅渲染(浅渲染仅渲染该特定组件并跳过子组件),该组件被WithRouter中的组件包裹。

2020-07-22