我如何用 throw e 在开玩笑行中进行测试?

And*_*eea 5 jestjs react-native

如何在玩笑错误情况下进行测试?这就是我所做的:我不知道是否存在如何测试它的方法。

it ('the fetch fails and throw an error', async () => {
      let response = {
        status: 400,
        body: 
        {
          base : "RON",
          date: "2019-08-01",
          rates: {"error": 'error'}
        }
      };
      fetch.mockReject(response)
      try {
        await fetchData();
      } catch (e) {
        expect(e).toEqual(response);
        expect(await fetchData()).rejects.toThrow(e);
      }
    });
Run Code Online (Sandbox Code Playgroud)

这是代码:

 fetchData = async () => {
    try {
      const response = await fetch('https://api.exo/latest?base=RON');
      const data = await response.json();
      return data;
    } catch (e) {
      throw e;
    }
  };
Run Code Online (Sandbox Code Playgroud)

sky*_*yer 2

Expect.asserts来拯救

it ('the fetch fails and throw an error', async () => {
  expect.assertions(1);
  let response = {
    status: 400,
    body: {
      base : "RON",
      date: "2019-08-01",
      rates: {"error": 'error'}
    }
  };
  fetch.mockReject(response)
  try {
    await fetchData();
  } catch (e) {
    expect(e).toEqual(response);
  }
});
Run Code Online (Sandbox Code Playgroud)

一旦没有抛出异常,测试就会失败。它具有以下优点expect().toThrown

  1. 你不必返回 Promise 来it()使其工作
  2. 更容易断言几个相关的异常或顺序操作失败
  3. 在捕获的错误上运行部分匹配更容易(例如expect(e).toMatchObject({})跳过当前测试用例中您不关心的一些数据)

至于缺点 - 添加新断言后必须手动更新数字