用axios调用进行笑话测试

时间:2020-05-02 01:36:17

标签: reactjs jestjs

我无法为此代码块设置一个公正的测试用例。

fetchCustomers = () => {
    axios
      .get(URL)
      .then((response) => {
        this.setState({ customers: response });
      })
      .catch((error) => {
        console.log(error);
      });
  };

这是我到目前为止尝试过的

fetchMock.get("/api/customer/3", () => {
      return [{id:1, name: 'customer1', number: 23}];
    });

    wrapper.instance().fetchCustomers();

    expect(wrapper.state()).toEqual({
      customers: [{id:1, name: 'customer1', number: 23}]
    });

当我查看代码覆盖率时,它只是告诉我我还没有到达层叠和错误的那一部分。

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

fetchCustomers的问题在于它不返回承诺并且不能被链接。即使当前在组件中也可以使用,这也会使测试更加困难,并阻止fetchCustomers与其他方法组合。

应该是:

fetchCustomers = () => {
    return axios
      ...

成功响应的测试方式如下:

fetchMock.get(...); // mock with 200 and data
jest.spyOn(axios, 'get');

await wrapper.instance().fetchCustomers();

expect(axios.get).toHaveBeenCalledWith(...);
expect(wrapper.state()).toEqual({...});

失败响应的测试方式如下:

fetchMock.get(...); // mock with 500
jest.spyOn(axios, 'get');
jest.spyOn(console, 'log');

await wrapper.instance().fetchCustomers();

expect(axios.get).toHaveBeenCalledWith(...);
expect(console.log).toHaveBeenCalledWith(expect.any(Error));
expect(wrapper.state()).toEqual({});