如何使用moxios测试异步功能? [英] how to test async function making use of moxios?
本文介绍了如何使用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.但是我的两个测试都失败了
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
推荐答案
来自sendFormData
的承诺将被忽略,这会导致竞争状况.
A promise from sendFormData
is ignored, this results in race condition.
可能应该是:
wrapper.setState({ uploading: true });
await wrapper.instance().sendFormData("dummydata");
expect(props.onFileNameChange).toHaveBeenCalledWith(data);
expect(wrapper.state("uploading")).toBe(false);
在这种情况下,Spec功能必须为async
.
Spec function needs to be async
in this case.
这篇关于如何使用moxios测试异步功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文