我正在尝试为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()和其他一些变体,只是不知道如何使它工作。
您正在使用:
expect(fn).toThrow(e)
但是如果你看一下函数注释(expected is string):
294 /**
295 * Matcher that checks that the expected exception was thrown by the actual.
296 *
297 * @param {String} expected
298 */
299 jasmine.Matchers.prototype.toThrow = function(expected) {
我想你应该这样写(使用lambda - anonymous函数):
expect(function() { parser.parse(raw); } ).toThrow("Parsing is not possible");
下面的例子证实了这一点:
expect(function () {throw new Error("Parsing is not possible")}).toThrow("Parsing is not possible");
Douglas Crockford强烈推荐这种方法,而不是使用“throw new Error()”(原型):
throw {
name: "Error",
message: "Parsing is not possible"
}