如何使用moxios测试异步功能?
how to test async function making use of moxios?
考虑以下反应代码。
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);
}
};
这是测试
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);
});
如您所见,sendFormData
应该调用 this.props.onFileNamechange
。并且它还应该将状态上传设置为 true。但是我的两个测试都失败了
来自 sendFormData
的承诺被忽略,这导致竞争条件。
可能应该是:
wrapper.setState({ uploading: true });
await wrapper.instance().sendFormData("dummydata");
expect(props.onFileNameChange).toHaveBeenCalledWith(data);
expect(wrapper.state("uploading")).toBe(false);
在这种情况下,规范函数需要 async
。
考虑以下反应代码。
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);
}
};
这是测试
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);
});
如您所见,sendFormData
应该调用 this.props.onFileNamechange
。并且它还应该将状态上传设置为 true。但是我的两个测试都失败了
来自 sendFormData
的承诺被忽略,这导致竞争条件。
可能应该是:
wrapper.setState({ uploading: true });
await wrapper.instance().sendFormData("dummydata");
expect(props.onFileNameChange).toHaveBeenCalledWith(data);
expect(wrapper.state("uploading")).toBe(false);
在这种情况下,规范函数需要 async
。