throws()


throws( block [, expected ] [, message ] )

Description: Test if a callback throws an exception, and optionally compare the thrown error.

  • throws( block [, expected ] [, message ] )

    • block
      Type: Function()
      Function to execute
    • expected
      Type: Object
      Error Object (instance), 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
      Type: String
      A 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.

Example:

Assert the correct error message is received for a custom error object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
QUnit.test( "throws", function( assert ) {
function CustomError( message ) {
this.message = message;
}
CustomError.prototype.toString = function() {
return this.message;
};
assert.throws(
function() {
throw "error"
},
"throws with just a message, not using the 'expected' argument"
);
assert.throws(
function() {
throw new CustomError("some error description");
},
/description/,
"raised error message contains 'description'"
);
assert.throws(
function() {
throw new CustomError();
},
CustomError,
"raised error is an instance of CustomError"
);
assert.throws(
function() {
throw new CustomError("some error description");
},
new CustomError("some error description"),
"raised error instance matches the CustomError instance"
);
assert.throws(
function() {
throw new CustomError("some error description");
},
function( err ) {
return err.toString() === "some error description";
},
"raised error instance satisfies the callback function"
);
});