【问题标题】:how to test async function making use of moxios?如何使用 moxios 测试异步功能?
【发布时间】:2018-10-26 08:18:15
【问题描述】:

考虑以下反应代码。

 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。但是我的两个测试都失败了

【问题讨论】:

    标签: reactjs jestjs enzyme moxios


    【解决方案1】:

    来自sendFormData 的承诺被忽略,这会导致竞争条件。

    应该是这样的:

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

    在这种情况下,规范函数需要为async

    【讨论】:

      猜你喜欢
      • 2021-12-29
      • 2019-11-01
      • 2021-01-18
      • 1970-01-01
      • 1970-01-01
      • 2018-06-03
      • 2013-08-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多