【问题标题】:Jest testing with axios call用 axios 调用开玩笑测试
【发布时间】:2020-08-16 14:04:36
【问题描述】:

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

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}]
    });

当我查看我的代码覆盖率时,它只是告诉我我没有到达级联的 then 部分和错误。

任何帮助将不胜感激!

【问题讨论】:

  • 这与 axios 是异步的(promise)有关,并且 jest 不能很好地处理异步代码(如 Promise)。但是,有一个解决方法mentioned here,您可以通过立即解决它来刷新承诺,然后对结果进行断言。另外注意,避免使用console.log(error),因为它更难测试(你必须模拟console.log,它会在没有UI指示的情况下静默失败);相反,将错误设置为 state。
  • @MattCarlotta 我必须补充一点,大多数时候这不是开玩笑,而是开发人员的错。当代码准备好测试时,没有必要刷新承诺。
  • 什么是fetchMock?实现取决于它。

标签: reactjs jestjs


【解决方案1】:

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({});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-05
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    • 2020-03-15
    相关资源
    最近更新 更多