我如何用 throw e 开玩笑地进行测试? [英] How I can test in jest line with throw e?
本文介绍了我如何用 throw 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;
}
};
推荐答案
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);
}
});
一旦没有异常抛出,测试就会失败.它比 expect().toThrown
有优势:
Test will fail once no exception is thrown. It has advantages over expect().toThrown
:
- 您不必在
it()
中返回 Promise 即可使其工作 - 更容易断言多个相关异常或顺序操作失败
- 在捕获的错误上运行部分匹配更容易(比如使用
expect(e).toMatchObject({})
跳过一些你在当前测试用例中不关心的数据)
- you don't have to return Promise in your
it()
to make it work - it's easier to assert several related exceptions or sequential actions failed
- 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
这篇关于我如何用 throw e 开玩笑地进行测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文