【问题标题】:Jest - How To Test a Fetch() Call That Returns A Rejected Promise?Jest - 如何测试返回被拒绝承诺的 Fetch() 调用?
【发布时间】:2022-01-23 03:58:25
【问题描述】:

我有以下函数使用fetch() 进行 API 调用:

export async function fetchCars(dealershipId) {
  return request('path/to/endpoint/' + dealershipId)
    .then((response) => {
      if (response.ok === false) {
        return Promise.reject();
      }
      return response.json();
    })
    .then((cars) => {
      return parseMyCars(cars);
    });
}

我想测试调用何时失败(特别是返回return Promise.reject() 时)。我现在有以下 Jest 测试:

(fetch as jest.Mock).mockImplementation(() =>
    Promise.resolve({ ok: false })
);
const result = await fetchCars(1);
expect(request).toHaveBeenCalledWith('/path/to/endpoint/1');
expect(result).toEqual(Promise.reject());

但我在运行测试时收到Failed: undefined 消息。我试过使用:

(fetch as jest.Mock).mockRejectedValue(() =>
  Promise.resolve({ ok: false })
);

但收到类似的Failed: [Function anonymous] 消息。

在这里测试被拒绝的承诺的正确方法是什么?

【问题讨论】:

  • const result = await fetchCars(1); 抛出一个错误,因为 promise 被拒绝,所以测试失败,函数调用结束并且没有达到断言。 expect(result).toEqual(Promise.reject()); 无论如何都没有意义 - 等待被拒绝的承诺的结果不是被拒绝的承诺,而是抛出错误。另请注意,测试错误总是很棘手,因为您可能会意外地编写非错误路径为误报的代码。根据jestjs.io/docs/asynchronous,您可能想使用.rejects

标签: javascript jestjs ts-jest jest-fetch-mock


【解决方案1】:

有几种方法可以正确处理这个问题。我认为问题在于你在等待你的承诺。

如果你打算使用 await 那么你必须等待期望:

const result = fetchCars(1);
await expect(result).toEqual(Promise.reject());
// ✅ Correct setup

或者您可以只返回未等待的承诺:

const result = fetchCars(1);
return expect(result).toEqual(Promise.reject());
// ✅ Correct setup

如果您没有返回或等待预期,那么您可能会注意到您得到了误报:

const result = fetchCars(1);
expect(result).toEqual(Promise.reject());
// ❌ False positive!

我创建了一个codesandbox example 向您展示如何模拟 fetch 函数以及如何正确设置测试,包括不正确的方法。试一试右上角的“测试”选项卡。

【讨论】:

    【解决方案2】:

    您的测试失败,因为它引发了异常。您需要捕获该异常,有很多方法可以做到这一点,使用rejects helper 就是其中之一:

    it("should fail", async () => {
        (window.fetch as jest.Mock).mockResolvedValueOnce({
          ok: false,
        });
        await expect(fetchCars(1)).rejects.toEqual(/* error you are expecting*/);
    });
    

    【讨论】:

      猜你喜欢
      • 2018-11-22
      • 2018-02-25
      • 1970-01-01
      • 1970-01-01
      • 2020-07-06
      • 1970-01-01
      • 2015-09-27
      • 2015-12-25
      • 2015-10-28
      相关资源
      最近更新 更多