From c0f90e2010f0c14ba931bbadd9668a498cd71fce Mon Sep 17 00:00:00 2001 From: Satoshi Nakamura Date: Thu, 5 Jul 2012 17:53:00 +0900 Subject: [PATCH] Check the type of a thrown exception with should.throw(). --- lib/should.js | 6 +++++- test/should.test.js | 24 ++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/lib/should.js b/lib/should.js index 93faf4c..84c98ba 100644 --- a/lib/should.js +++ b/lib/should.js @@ -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; } } } diff --git a/test/should.test.js b/test/should.test.js index 8f0fbf1..2b16491 100644 --- a/test/should.test.js +++ b/test/should.test.js @@ -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(); @@ -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"); } };