-->

断言函数抛出的异常与Qunit(Asserting that a function throws e

2019-06-23 17:23发布

我是新来Qunit和单元测试。

我试图找出是什么,以及如何测试以下功能。 它并没有做太多的时刻,但我想断言,如果我通过它正在引发的错误不正确的值:

function attrToggle (panel, attr) {
    'use strict';

    if (!panel) { throw new Error('Panel is not defined'); }
    if (!attr) { throw new Error('Attr is not defined'); }
    if (typeof panel !== 'string') { throw new Error('Panel is not a string'); }
    if (typeof attr !== 'string') { throw new Error('Attr is not a string'); }
    if (arguments.length !== 2) { throw new Error('There should be only two arguments passed to this function')}

};

我该如何去断言,如果任何一个条件不满足的错误将被抛出?

我想看看Qunit的“加薪”的断言,但认为我误解了。 我的解释是,如果一个错误被抛出测试通过。

所以,如果我测试过这样的事情:

test("a test", function () {
    raises(function () {
        throw attrToggle([], []);
    }, attrToggle, "must throw error to pass");
});

测试应该通过,因为错误抛出。

Answer 1:

几件事情错了,工作的例子是在http://jsfiddle.net/Z8QxA/1/

主要的问题是要传递错误的东西作为第二个参数raises() 在第二个参数是用来验证正确的错误已被抛出,那么它要么需要一个正则表达式,错误的类型,或回调,让你做你自己验证的构造。

因此,在你的榜样,你路过attrToggle因为这会抛出错误的类型。 你的代码实际上抛出一个Error类型等检查实际上失败。 传递Error的第二个参数的工作,只要你想:

test("a test", function () {
    raises(function () {
        attrToggle([], []);
    }, Error, "Must throw error to pass.");
});

其次,你不需要throw打电话时关键字attrToggle()raises()



Answer 2:

是啊,你很可能是正确的。 raises()当你测试代码期望抛出的错误。

通常我用try-catch我的功能赶不正确的参数类型。 我用raises()来测试throw 。 如果我把一个不正确的值作为参数,并且测试不符合以raises()然后有什么东西没有抓到。



文章来源: Asserting that a function throws exceptions with Qunit