首页 文章

测试反应组件包含在withRouter中(最好使用jest /酶)

提问于
浏览
12

我有一个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中而无法呈现?我们如何测试这些类型的组件?

3 回答

  • -1

    我做了什么解决了这个问题:

    在“this.props.match.params.id”中使用了post组件

    在测试用例中

    const miniProps = {
        otherProps,
        match:{params:{id:'112'}}
    };
    
    const wrapper = shallow();
    
  • 1

    通常,如果我们尝试测试这样的组件,我们将无法呈现它,因为它被包含在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进行浅层渲染(浅层渲染仅渲染该特定组件并跳过子组件),这是WithRouter中的包装组件 .

  • 18

    浅渲染只会渲染一个级别,这是它的规格的一部分 .

    你可以使用Mount来渲染整个树,但我认为你不能限制它渲染多少层 .

    在任何情况下,当使用高阶组件时,我通常也会导出基本组件(在包装之前),这样我就可以在没有包装器的情况下完成所有测试,并简单地为所需的提供者传递模拟 .

    与带有redux的 Connect 组件相同的是,您导出常规组件并测试其上的不同道具,而不是连接的道具 .

    还要注意,有些 with... 包装器不公开内部实例(有些没有,但有些没有),所以测试你自己的组件而不是包装也有帮助 .

相关问题