'Test the lifecycle methods of a connected component + ReactJs + Jest
I am trying to test the componentWillRecieveProps of a connected component. Since I can't shallow render the component as it needs to be wrapped in a Provider, I am updating the props by setProps method of the child component.
setProps() usually will call the component lifecycle methods but since the testing here is on the child component, setProps() is not re rendering the wrapper and thus I am unable to test componentWillRecieveProps with new Props.
Any suggestions to test the connected component lifecycle methods?
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
});
Solution 1:[1]
I think you can export non connected "MyComponent" for testing purposes. This way you can simulate prop changes and verify your render output easily.
For example,
MyComponent.jsx
export class MyComponentComp extends React.Component<Props, State> {
// use this for testing
}
export default connect(mapStateToProps, dispatchToProps)(MyComponentComp)
"componentWillReceiveProps" is deprecated may be try updating that as well.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Oshan Abeykoon |
