throws()


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

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

When testing code that is expected to throw an exception based on a specific set of circumstances, use 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
test( "throws", function() {
function CustomError( message ) {
this.message = message;
}
CustomError.prototype.toString = function() {
return this.message;
};
throws(
function() {
throw "error"
},
"throws with just a message, not using the 'expected' argument"
);
throws(
function() {
throw new CustomError();
},
CustomError,
"raised error is an instance of CustomError"
);
throws(
function() {
throw new CustomError("some error description");
},
/description/,
"raised error message contains 'description'"
);
});