问题描述
我正在使用一些代码,在这些代码中,我需要测试函数抛出的异常的类型(是TypeError,ReferenceError等吗?).
I'm working with some code where I need to test the type of an exception thrown by a 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 in Jest and couldn't find how to easily do that. Is it even possible?
推荐答案
在Jest中,您必须将函数传递到expect(function).toThrow(<blank or type of error>)
.
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);
});
或者如果您还想检查错误消息:
Or if you also want to check for error message:
test("Test description", () => {
const t = () => {
throw new TypeError("UNKNOWN ERROR");
};
expect(t).toThrow(TypeError);
expect(t).toThrow("UNKNOWN ERROR");
});
如果需要测试现有函数是否带有一组参数,则必须将其包装在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中测试抛出的异常的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!