我正在尝试为Jasmine测试框架编写一个测试,该测试预计会出现错误。目前,我正在使用来自GitHub的Jasmine Node.js集成。
在我的Node.js模块中,我有以下代码:
throw new Error("Parsing is not possible");
现在我试着写一个测试,期望这个错误:
describe('my suite...', function() {
[..]
it('should not parse foo', function() {
[..]
expect(parser.parse(raw)).toThrow(new Error("Parsing is not possible"));
});
});
我还尝试了Error()和其他一些变体,只是不知道如何使它工作。
如前所述,需要将函数传递给toThrow,因为它是您在测试中描述的函数:“I expect this function to throw x”
expect(() => parser.parse(raw))
.toThrow(new Error('Parsing is not possible'));
如果使用茉莉花-匹配器,你也可以使用以下其中之一,当他们适合的情况;
// I just want to know that an error was
// thrown and nothing more about it
expect(() => parser.parse(raw))
.toThrowAnyError();
or
// I just want to know that an error of
// a given type was thrown and nothing more
expect(() => parser.parse(raw))
.toThrowErrorOfType(TypeError);
对我来说,发布的解决方案不起作用,它一直抛出这个错误:
错误:期望函数抛出异常。
我后来意识到,我期望抛出错误的函数是一个异步函数,并期望承诺被拒绝,然后抛出错误,这就是我在我的代码中所做的:
throw new Error('REQUEST ID NOT FOUND');
这就是我在测试中所做的,它起作用了:
it('Test should throw error if request not found', willResolve(() => {
const promise = service.getRequestStatus('request-id');
return expectToReject(promise).then((err) => {
expect(err.message).toEqual('REQUEST NOT FOUND');
});
}));