簡體   English   中英

開玩笑 - 如何測試返回被拒絕的 Promise 的 Fetch() 調用?

[英]Jest - How To Test a Fetch() Call That Returns A Rejected Promise?

我有以下 function 使用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]消息。

在這里測試被拒絕的 promise 的正確方法是什么?

有幾種方法可以正確處理這個問題。 我認為問題在於您正在等待您的 promise。

如果您打算使用 await 那么您必須等待期望:

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

或者您可以返回未等待的 promise:

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

如果您不返回或等待預期,那么您可能會注意到您得到了誤報:

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

我創建了一個代碼框示例,向您展示如何模擬獲取 function 以及如何正確設置測試,包括不正確的方法。 試一試右上角的“測試”選項卡。

您的測試失敗,因為它引發了異常。 您需要捕獲該異常,有很多方法可以做到這一點,使用拒絕助手就是其中之一:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM