I have a simple form as a React component. Upon clicking a button, handleSubmit() is called which makes a callout and clears the form if the callout is successful. I tried making a Jest unit test that tests if the form is cleared upon submission.
it('handles form submission', () => {
Amplify.API.post = jest.fn().mockImplementation(() => Promise.resolve());
EventEmitter.emit = jest.fn().mockImplementation(() => Promise.resolve());
wrapper.setState({
diocese: {
name: 'My New Diocese',
id: '123',
generalCollectionOnly: false,
aggregatePayments: false,
aggregatePledges: false,
},
});
footer.children().find(Button).at(1).simulate('click');
expect(wrapper.state().diocese.name).toEqual('');
});
After debugging this, I can see that the form is submitted successfully and calls this.setState():
this.setState(() => ({
diocese: {
id: '',
name: '',
generalCollectionOnly: false,
aggregatePledges: false,
aggregatePayments: false,
},
isLoading: false,
}));
However, the expect statement fails because the name still shows 'My New Diocese' even though it should be cleared. After doing some research, I thought that updating the wrapper would help:
wrapper.update();
However, it still shows that the component's state has not been cleared. Why is the state not updating in the test?
Thank you for the feedback. The problem was caused by the handleSubmit() doing asynchronous work. Adding an await in the Jest unit test fixed the issue. This is how the test looks:
it('handles form submission', async () => {
Amplify.API.post = jest.fn().mockImplementation(() => Promise.resolve());
EventEmitter.emit = jest.fn().mockImplementation(() => Promise.resolve());
wrapper.setState({
diocese: {
name: 'My New Diocese',
id: '123',
generalCollectionOnly: false,
aggregatePayments: false,
aggregatePledges: false,
},
});
await footer.children().find(Button).at(1).simulate('click');
expect(wrapper.state().diocese.name).toEqual('');
});
The test passes now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With