问题描述
我正在使用一些代码,我需要测试函数抛出的异常类型(是TypeError,ReferenceError等)。
I'm working with some code where I need to test type of exception thrown by function (Is it TypeError, ReferenceError etc.).
我当前的测试框架是AVA,我可以测试它作为第二个参数 t.throws
方法,就像这里:
My current testing framework is AVA and I can test it as a second argument t.throws
method, like here:
it('should throw Error with message \'UNKNOWN ERROR\' when no params were passed', (t) => {
const error = t.throws(() => {
throwError();
}, TypeError);
t.is(error.message, 'UNKNOWN ERROR');
});
我开始将测试改写为Jest,但却找不到如何轻松做到这一点。甚至可能吗?
I started rewriting my tests to Jest and couldn't find how to easily do that. Is it even possible?
推荐答案
在Jest中你必须将一个函数传递给expect(function).toThrow(空格或类型错误)。
In Jest you have to pass a function into expect(function).toThrow(blank or type of error).
示例:
test("Test description", () => {
const t = () => {
throw new TypeError();
};
expect(t).toThrow(TypeError);
});
如果你需要测试现有函数是否抛出一组参数,你必须换行它位于expect()中的匿名函数内。
If you need to test an existing function whether it throws with a set of arguments, you have to wrap it inside an anonymous function in expect().
示例:
test("Test description", () => {
expect(() => {http.get(yourUrl, yourCallbackFn)}).toThrow(TypeError);
});
这篇关于如何在Jest中测试抛出异常的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!