如何编写一个期望在Jasmine中引发错误的测试?

JavaScript

Itachi小卤蛋凯

2020-03-12

我正在尝试为Jasmine测试框架编写测试,该测试会出现错误。目前,我正在使用来自GitHubJasmine Node.js集成

在我的Node模块中,我有以下代码:

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()了其他一些变体,只是想不通如何使其工作。

第1334篇《如何编写一个期望在Jasmine中引发错误的测试?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
Gil米亚卡卡西 2020.03.12

对于喜欢咖啡的人

expect( => someMethodCall(arg1, arg2)).toThrow()
番长梅 2020.03.12

比创建匿名函数(其唯一目的是包装另一个函数)更优雅的解决方案是使用es5 bind函数。bind函数创建一个新函数,该新函数在被调用时将其this关键字设置为所提供的值,并在调用新函数时提供给定的参数序列。

代替:

expect(function () { parser.parse(raw, config); } ).toThrow("Parsing is not possible");

考虑:

expect(parser.parse.bind(parser, raw, config)).toThrow("Parsing is not possible");

绑定语法允许您测试具有不同this值的函数,并且我认为使测试更具可读性。另请参阅:https : //stackoverflow.com/a/13233194/1248889

西门十三LEY 2020.03.12

您正在使用:

expect(fn).toThrow(e)

但是,如果您要看一下函数注释(预期是字符串):

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-匿名函数):

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)强烈建议采用这种方法,而不要使用“抛出新的Error()”(原型方法):

throw {
   name: "Error",
   message: "Parsing is not possible"
}
Sam飞云 2020.03.12

您应该将函数传递给expect(...)调用。您在此处的代码:

// incorrect:
expect(parser.parse(raw)).toThrow(new Error("Parsing is not possible"));

正在尝试实际调用 parser.parse(raw)以将结果传递到expect(...)

尝试改用匿名函数:

expect( function(){ parser.parse(raw); } ).toThrow(new Error("Parsing is not possible"));

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android