如何使用moxios测试异步功能?

时间:2018-10-26 08:18:15

标签: reactjs jestjs enzyme 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。但是我的两个测试都失败了

1 个答案:

答案 0 :(得分:1)

来自sendFormData的承诺将被忽略,这会导致竞争状态。

可能应该是:

wrapper.setState({ uploading: true });
await wrapper.instance().sendFormData("dummydata");
expect(props.onFileNameChange).toHaveBeenCalledWith(data);
expect(wrapper.state("uploading")).toBe(false);

在这种情况下,规范函数必须为async