docs/api/assert/throws.md
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:
errorValue instanceof expectedMatcher.true or false.| 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.
assert.rejects() for asynchronous errors.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';
}
);
});