【问题标题】:Test the lifecycle methods of a connected component + ReactJs + Jest测试一个连接组件 + ReactJs + Jest 的生命周期方法
【发布时间】:2022-02-09 20:03:01
【问题描述】:

我正在尝试测试已连接组件的 componentWillRecieveProps。由于我不能浅渲染组件,因为它需要包装在 Provider 中,我正在通过子组件的 setProps 方法更新道具。

setProps() 通常会调用组件生命周期方法,但由于这里的测试是在子组件上进行的,所以 setProps() 不会重新渲染包装器,因此我无法使用新的 Props 测试 componentWillRecieveProps。

对测试连接组件生命周期方法有什么建议吗?

 test('calls componentWillReceiveProps', () => {
    const willReceiveProps = jest.fn();
    const props = {
        title: "Order",
        history,
        ordersStatus: true,
        status: 'loaded',
        dispatch: jest.fn()
    }

    const newProps = {
        ...props,
        status: 'failed'
    }

    wrapper = mount(<Provider store={store}><MyComponent {...props} /></Provider>)
    wrapper.setProps({ children: <MyComponent {...newProps} /> });
    // New props are updated from above, expect componentWillReceiveProps to be called here
    OrderpickupDashboard.prototype.componentWillReceiveProps = willReceiveProps;
    wrapper.update();
    expect(willReceiveProps).toBeTruthy();
    // expect(willReceiveProps).toBeCalled();
    // This statement isn't working as the lifecycle method isn't called, how can we make the 
       test call componentWillReceiveProps
  
});

【问题讨论】:

  • componentWillRecieveProps 已弃用,请改用componentDidUpdatereactjs.org/docs/…
  • 我正在做一个遗留项目,所以无法避免

标签: javascript reactjs redux jestjs


【解决方案1】:

我认为您可以出于测试目的导出未连接的“MyComponent”。通过这种方式,您可以轻松模拟道具更改并验证您的渲染输出。

例如,

MyComponent.jsx

export class MyComponentComp extends React.Component<Props, State> {
 // use this for testing
}

export default connect(mapStateToProps, dispatchToProps)(MyComponentComp)

“componentWillReceiveProps”已弃用,也可以尝试更新它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-06
    • 1970-01-01
    • 2017-05-21
    • 1970-01-01
    • 2017-05-18
    • 2019-11-27
    • 1970-01-01
    • 2023-03-09
    相关资源
    最近更新 更多