Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/444.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 断言函数使用Qunit抛出异常_Javascript_Jquery_Unit Testing_Qunit - Fatal编程技术网

Javascript 断言函数使用Qunit抛出异常

Javascript 断言函数使用Qunit抛出异常,javascript,jquery,unit-testing,qunit,Javascript,Jquery,Unit Testing,Qunit,我不熟悉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

我不熟悉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')}

};
如果不满足这些条件中的任何一个,我如何断言将抛出错误

我试图看看昆特的“提高”断言,但认为我误解了它。我的解释是,如果抛出错误,测试就会通过

所以,如果我测试了这样的东西:

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

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

是的,您基本上做对了。测试代码时预期会引发错误


通常我使用函数的
try-catch
来捕获不正确的参数类型。我使用
raises()。如果我将不正确的值作为参数,并且测试不符合
raises()

主要问题是,您将错误的内容作为第二个参数传递给
raises()
。用于验证是否抛出了正确的错误,因此它需要一个正则表达式、一个错误类型的构造函数或一个允许您自己进行验证的回调

因此,在您的示例中,您将
attrttoggle
作为将抛出的错误类型传递。您的代码实际上抛出了一个
错误
类型,因此检查实际上失败了。作为第二个参数传递
Error
,可根据需要工作:

test("a test", function () {
    raises(function () {
        attrToggle([], []);
    }, Error, "Must throw error to pass.");
});
其次,在
raises()
内部调用
attrttoggle()
时,不需要使用
throw
关键字