}
};
-function _throws (shouldThrow, block, err, message) {
- var exception = null,
- threw = false,
- typematters = true;
-
- message = message || "";
-
- //handle optional arguments
- if (arguments.length == 3) {
- if (typeof(err) == "string") {
- message = err;
- typematters = false;
+function expectedException(actual, expected) {
+ if (!actual || !expected) {
+ return false;
+ }
+
+ if (expected instanceof RegExp) {
+ if (expected.test(actual)) {
+ return true;
}
- } else if (arguments.length == 2) {
- typematters = false;
+ } else if (actual instanceof expected || expected.call({}, actual) !== false) {
+ return true;
+ }
+}
+
+function _throws (shouldThrow, block, expected, message) {
+ var actual;
+
+ if (typeof expected === "string") {
+ message = expected;
+ expected = null;
}
try {
block();
} catch (e) {
- threw = true;
- exception = e;
+ actual = e;
}
- if (shouldThrow && !threw) {
- fail( "Missing expected exception"
- + (err && err.name ? " ("+err.name+")." : '.')
- + (message ? " " + message : "")
- );
+ message = (expected && expected.name ? " (" + expected.name + ")." : ".")
+ + (message ? " " + message : ".");
+
+ if (shouldThrow && !actual) {
+ fail("Missing expected exception" + message);
}
- if (!shouldThrow && threw && typematters && exception instanceof err) {
- fail( "Got unwanted exception"
- + (err && err.name ? " ("+err.name+")." : '.')
- + (message ? " " + message : "")
- );
+
+ if (!shouldThrow && expectedException(actual, expected)) {
+ fail("Got unwanted exception" + message);
}
- if ((shouldThrow && threw && typematters && !(exception instanceof err)) ||
- (!shouldThrow && threw)) {
- throw exception;
+
+ if ((shouldThrow && actual && expected && !expectedException(actual, expected)) ||
+ (!shouldThrow && actual)) {
+ throw actual;
}
-};
+}
// 11. Expected to throw an error:
// assert.throws(block, Error_opt, message_opt);
assert.throws(function () {assert.ifError(new Error('test error'))});
assert.doesNotThrow(function(){assert.ifError(null)});
assert.doesNotThrow(function(){assert.ifError()});
+
+// use a RegExp to validate error message
+a.throws(makeBlock(thrower, TypeError), /test/ );
+
+// use a fn to validate error object
+a.throws(makeBlock(thrower, TypeError), function(err) {
+ if (!(err instanceof TypeError) || !/test/.test(err)) {
+ return false;
+ }
+});