我怎样才能用抛出e来进行开玩笑的测试? [英] How I can test in jest line with throw e?

查看:412
本文介绍了我怎样才能用抛出e来进行开玩笑的测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How I can test in jest error case? This is what I do: I don't know if exist a method how to test this.

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

推荐答案

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:

Test will fail once no exception is thrown. It has advantages over expect().toThrown:

  1. 您不必在it()中返回Promise即可使其正常工作
  2. 断言几个相关异常或顺序操作失败更容易
  3. 对捕获到的错误进行部分匹配会更容易(例如,使用expect(e).toMatchObject({})跳过当前测试用例中不需要的数据)
  1. you don't have to return Promise in your it() to make it work
  2. it's easier to assert several related exceptions or sequential actions failed
  3. it's easier to run partial matching over error caught(say with expect(e).toMatchObject({}) to skip some data you don't care about in current test case)

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

As for disadvantages - you have to update number manually after adding new assertions

这篇关于我怎样才能用抛出e来进行开玩笑的测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆