【发布时间】: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已弃用,请改用componentDidUpdate。 reactjs.org/docs/… -
我正在做一个遗留项目,所以无法避免
标签: javascript reactjs redux jestjs