我该如何在抛出E的笑话行中测试?

时间:2019-08-01 13:03:26

标签: react-native jestjs

如何在开玩笑的错误情况下进行测试? 这是我的工作: 我不知道是否存在一种方法来测试这一点。

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);
      }
    });

这是代码:

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

2 个答案:

答案 0 :(得分:0)

您可以通过以下方式进行操作:

async function throws () {
  throw new Error('error')
}

test('promise throws', async () => {
  await expect(throws()).rejects.toThrow()
})

test('the fetch fails with an error', async () => {
  await expect(throws()).rejects.toThrow('error');
});

test('the fetch fails with an error', () => {
  return expect(throws()).rejects.toMatch('error');
});

了解更多docs

答案 1 :(得分:0)

expect.assertions进行救援

it ('the fetch fails and throw an error', async () => {
  jest.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);
  }
});

一旦没有异常抛出,测试将失败。与expect().toThrown相比,它具有以下优势:

  1. 您不必在自己的it()中返回Promise即可使其正常工作
  2. 断言多个相关异常或顺序操作失败更容易
  3. 对捕获的错误进行部分匹配比较容易(例如,用expect(e).toMatchObject({})跳过在当前测试用例中不需要的数据)

对于缺点-您必须在添加新的断言之后手动更新编号