繁体   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