Skip to content

Commit

Permalink
Merge pull request tj#79 from snakamura/throw_type
Browse files Browse the repository at this point in the history
Check the type of a thrown exception with should.throw().
  • Loading branch information
tj committed Jul 17, 2012
2 parents 6a47b14 + c0f90e2 commit dbc054d
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
6 changes: 5 additions & 1 deletion lib/should.js
Original file line number Diff line number Diff line change
Expand Up @@ -674,13 +674,17 @@ Assertion.prototype = {
ok = message == err.message;
} else if (message instanceof RegExp) {
ok = message.test(err.message);
} else if ('function' == typeof message) {
ok = err instanceof message;
}

if (message && !ok) {
if ('string' == typeof message) {
errorInfo = " with a message matching '" + message + "', but got '" + err.message + "'";
} else {
} else if (message instanceof RegExp) {
errorInfo = " with a message matching " + message + ", but got '" + err.message + "'";
} else if ('function' == typeof message) {
errorInfo = " of type " + message.name + ", but got " + err.constructor.name;
}
}
}
Expand Down
24 changes: 24 additions & 0 deletions test/should.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -575,6 +575,18 @@ module.exports = {
}, "expected an exception to be thrown with a message matching 'fail', but got 'error'");
},

'test throw() with type': function(){
(function(){ throw new Error('fail'); }).should.throw(Error);

err(function(){
(function(){}).should.throw(Error);
}, 'expected an exception to be thrown');

err(function(){
(function(){ throw 'error'; }).should.throw(Error);
}, "expected an exception to be thrown of type Error, but got String");
},

'test throwError()': function(){
(function(){}).should.not.throwError();
(function(){ throw new Error('fail') }).should.throwError();
Expand Down Expand Up @@ -612,6 +624,18 @@ module.exports = {
err(function(){
(function(){ throw new Error('error'); }).should.throwError('fail');
}, "expected an exception to be thrown with a message matching 'fail', but got 'error'");
},

'test throwError() with type': function(){
(function(){ throw new Error('fail'); }).should.throw(Error);

err(function(){
(function(){}).should.throw(Error);
}, 'expected an exception to be thrown');

err(function(){
(function(){ throw 'error'; }).should.throw(Error);
}, "expected an exception to be thrown of type Error, but got String");
}

};

0 comments on commit dbc054d

Please sign in to comment.