Consider the following react code.
sendFormData = async formData => {
try {
const image = await axios.post("/api/image-upload", formData);
this.props.onFileNameChange(image.data);
this.setState({
uploading: false
});
} catch (error) {
console.log("This errors is coming from ImageUpload.js");
console.log(error);
}
};
Here is the test
it("should set uploading back to false on file successful upload", () => {
const data = "dummydata";
moxios.stubRequest("/api/image-upload", {
status: 200,
response: data
});
const props = {
onFileNameChange: jest.fn()
};
const wrapper = shallow(<ImageUpload {...props} />);
wrapper.setState({ uploading: true });
wrapper.instance().sendFormData("dummydata");
wrapper.update();
expect(props.onFileNameChange).toHaveBeenCalledWith(data);
expect(wrapper.state("uploading")).toBe(false);
});
As you can see sendFormData
should call this.props.onFileNamechange
. and it also should set the state uploading to true. But both my tests are failing
A promise from sendFormData
is ignored, this results in race condition.
It likely should be:
wrapper.setState({ uploading: true });
await wrapper.instance().sendFormData("dummydata");
expect(props.onFileNameChange).toHaveBeenCalledWith(data);
expect(wrapper.state("uploading")).toBe(false);
Spec function needs to be async
in this case.