簡體   English   中英

JavaScript(ES6)和fetch():如何引發錯誤以便捕獲觸發器? (用Jest測試)

[英]JavaScript (ES6) and fetch(): How can I throw an error so that catch triggers? (Testing it with Jest)

直到現在,我還以為我在JavaScript方面還不錯。 我想為我的HTTP請求編寫一個輔助函數。 我用Jest測試過。 問題在於catch()部分不會被觸發。 首先讓我給您測試:

it("recognizes when a response's status is not okay", () => {
  fetch.mockResponseOnce(JSON.stringify({ ok: false }));

  expect.assertions(1);

  return getRequestWithoutHeader(fullTestUrl).catch(err => {
    expect(err.ok).toEqual(false);
  });
});

也許測試寫錯了,但失敗了。 無論如何,這里是我確實編寫的輔助函數。 我嘗試了不同的實現,但它們均未通過測試:

// Implementation one: with throw
export const getRequestWithoutHeader = fullUrlRoute =>
  fetch(fullUrlRoute).then(response =>
    response.json().then(json => {
      if (!response.ok) {
        throw Error(json);
      }
      return json;
    }, error => error)
  );

// Implementation two: with throw new
export const getRequestWithoutHeader = fullUrlRoute =>
  fetch(fullUrlRoute).then(response =>
    response.json().then(json => {
      if (!response.ok) {
        throw new Error(json);
      }
      return json;
    }, error => error)
  );

// Implementation three: With Promise.reject
export const getRequestWithoutHeader = fullUrlRoute =>
  fetch(fullUrlRoute).then(response =>
    response.json().then(json => {
      if (!response.ok) {
        return Promise.reject(json);
      }
      return json;
    }, error => error)
  );

// Implementation four: with new Promise
export const getRequestWithoutHeader = fullUrlRoute =>
  new Promise((resolve, reject) => {
    fetch(fullUrlRoute).then(response =>
      response.json().then(
        json => {
          if (!response.ok) {
            reject(json);
          }
          resolve(json);
        },
        error => reject(error)
      )
    );
  });

這些都不起作用。 其中一些會在測試中使用then返回,但是我希望兌現承諾。 我想觸發一個陷阱。

我該如何編寫此輔助函數?

你可以這樣嘗試

  fetch(fullUrlRoute)
  .then(response =>{
      if (response.ok) {
        return response.json();
      }
      else throw response
  })
  .then(json=> {
      console.log(json);
    })
  .catch(error =>{
      console.log(error)
   });

希望這對您有幫助

我最終要做的是:

我使用jest-fetch-mock模擬請求。

為了正確地拒絕了Promise,我不得不覆蓋了mockResponseOnce函數嘲諷的init參數。

這是測試最終的外觀:

  it("recognizes when a response's status is not okay", () => {
    fetch.mockResponseOnce(JSON.stringify({ someResponse: "someResponse" }), { status: 403 });
    expect.assertions(1);

    return getRequestWithHeader(fullTestUrl, article).catch(err => {
      expect(err.someResponse).toEqual("someResponse");
    });
  });

通過顯式設置狀態,它將自動在響應中設置ok: false ,從而觸發功能。

我還應用了SomePerfomance的技巧,並重構了如下函數:

export const getRequestWithoutHeader = fullUrlRoute =>
  fetch(fullUrlRoute)
    .then(response => {
      if (!response.ok) {
        return Promise.reject(response);
      }
      return response.json();
    })

暫無
暫無

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

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