断言函数抛出Qunit的exception

我是Qunit和unit testing的新手。

我试图找出测试以下function的内容和方法。 它目前没有做太多但我想断言如果我传递错误值的错误值:

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"); }); 

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

有些事情是错的,一个有效的例子是http://jsfiddle.net/Z8QxA/1/

主要问题是你将错误的东西作为第二个参数传递给raises() 。 第二个参数用于validation是否已抛出正确的错误,因此它要么是正则表达式,要么是错误类型的构造函数,要么是允许您自己进行validation的回调。

因此,在您的示例中,您将attrToggle作为将被抛出的错误类型传递。 您的代码实际上抛出了Error类型,因此检查实际上失败了。 传递Error因为第二个参数可以按您的方式工作:

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

其次,在raises()调用attrToggle()时不需要throw关键字。

是的,你几乎做对了。 raises()期望在测试代码时抛出错误。

通常我使用try-catch来捕获不正确的参数类型。 我使用raises()来测试throw 。 如果我将一个不正确的值作为参数,并且测试不符合raises()那么就没有抓到一些东西。