how to test async function making use of moxios?

℡╲_俬逩灬. 提交于 2021-02-10 17:29:20

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/53004395/how-to-test-async-function-making-use-of-moxios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!