Asserting that a function throws exceptions with Qunit

强颜欢笑 提交于 2019-12-19 05:34:31

问题


I am new to Qunit and unit testing.

I am trying to figure out what and how to test the following function. It does not do much at the moment but I wanted to assert that if I pass it incorrect values that errors are being thrown:

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')}

};

How do I go about asserting that an error will be thrown if any of these conditions are not met?

I tried to look at Qunit's 'raises' assertion but think I am misunderstanding it. My interpretation would be that the test passes if an error is thrown.

So if I tested something like this:

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

The test should pass because errors are thrown.


回答1:


A couple of things wrong, a working example is at http://jsfiddle.net/Z8QxA/1/

The main issue is that you are passing the wrong thing as the second argument to raises(). The second argument is used to verify that the correct Error has been thrown, so it either expects a regex, a constructor of the type of error, or a callback that allows you do your own verification.

So in your example, you were passing attrToggle as the type of error that would be thrown. Your code actually throws an Error type and so the check actually failed. Passing Error as the second argument works as you want:

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

Secondly, you don't need the throw keyword when calling attrToggle() inside raises().




回答2:


yup, you pretty much got it right. raises() expects a thrown error when you test a code.

Usually I use try-catch for my functions to catch incorrect argument types. I use raises() to test the throw. If I placed an incorrect value as an argument, and the test did not comply to raises() then something was not caught.



来源:https://stackoverflow.com/questions/10190392/asserting-that-a-function-throws-exceptions-with-qunit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!