We left the throws() assertion method to the end because it’s a bit different from the others. Its syntax is as follows.
Method syntax: throws | |
---|---|
throws(function[, expected][, message ]) | |
Verify that a callback throws an exception, and optionally compare the thrown error. | |
Parameters | |
function | (Function) The function to execute. |
expected | (Object|Function|RegExp) An Error object, an Error function (constructor), a RegExp that matches (or partially matches) the string representation, or a callback function that must return true to pass the assertion check. |
message | (String) An optional description of the assertion. If omitted, the message shown is “okay” in case of success and “failed” in case of failure. |
Returns | |
undefined |
This method is different from the others in that it doesn’t accept as its first argument a value to test but rather a function that’s expected to throw an error because the expected value is optional. To see it in action, let’s modify the isEven() function to throw an error if the parameter passed isn’t of type Number:
function isEven(number) {
if (typeof number !== 'number') {
throw new Error('The passed argument is not a number');
}
return number % 2 === 0;
}
To test that the error is thrown, you can write
assert.throws(
function() {
isEven('test');
},
new Error('The passed argument is not a number'),
'Passing a string throws an error'
);
In this case you pass the expected value in the form of the same Error instance you expect to be thrown. Alternatively, you can verify that the error message is what you expect by changing the previous assertion to use a regular expression:
assert.throws(
function() {
isEven('test');
},
/The argument passed is not a number/,
'Passing a string throws an error'
);
With the throws() method we’ve completed the overview of the assertion methods provided by QUnit to test synchronous code. To test asynchronous code like callbacks passed to jQuery’s Ajax functions, you need to learn an additional method. Let’s discover more.
Leave a Reply