assert.throws()
version added: 1.0.0.
Description
throws( blockFn, message = "" )
throws( blockFn, expectedMatcher, message = "" )
Test if a callback throws an exception, and optionally compare the thrown error.
| name | description |
|---|---|
blockFn (function) |
Function to execute |
expectedMatcher |
Expected error matcher |
message (string) |
Short description of the assertion |
When testing code that is expected to throw an exception based on a specific set of circumstances, use assert.throws() to catch the error object for testing and comparison.
The expectedMatcher argument can be:
- An Error object.
- An Error constructor, evaluated as
errorValue instanceof expectedMatcher. - A RegExp that matches (or partially matches) the string representation.
- A callback with your own custom validation, that returns
trueorfalse.
If you need to comply with classic ES3 syntax, such as in early versions of Closure Compiler, you can use assert.raises(), which is an alias for assert.throws(). It has the same signature and behaviour.
Changelog
| QUnit 2.12 | Added support for arrow functions as expectedMatcher callback function. |
| QUnit 1.9 | assert.raises() was renamed to assert.throws().The assert.raises() method remains supported as an alias. |
See also
- Use
assert.rejects()for asynchronous errors.
Examples
QUnit.test('throws example', function (assert) {
// simple check
assert.throws(function () {
throw new Error('boo');
});
// simple check
assert.throws(
function () {
throw new Error('boo');
},
'optional description here'
);
// match pattern on actual error
assert.throws(
function () {
throw new Error('some error');
},
/some error/,
'optional description here'
);
// using a custom error constructor
function CustomError (message) {
this.message = message;
}
CustomError.prototype.toString = function () {
return this.message;
};
// actual error is an instance of the expected constructor
assert.throws(
function () {
throw new CustomError('some error');
},
CustomError
);
// actual error has strictly equal `constructor`, `name` and `message` properties
// of the expected error object
assert.throws(
function () {
throw new CustomError('some error');
},
new CustomError('some error')
);
// custom validation arrow function
assert.throws(
function () {
throw new CustomError('some error');
},
(err) => err.toString() === 'some error'
);
// custom validation function
assert.throws(
function () {
throw new CustomError('some error');
},
function (err) {
return err.toString() === 'some error';
}
);
});