Browse Source

assert.throws can now accept as RegExp

makes validation of errors more flexible
v0.7.4-release
Oleg Slobodskoi 14 years ago
committed by Ryan Dahl
parent
commit
02083412eb
  1. 63
      lib/assert.js
  2. 10
      test/simple/test-assert.js

63
lib/assert.js

@ -239,47 +239,50 @@ assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
}
};
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);

10
test/simple/test-assert.js

@ -158,3 +158,13 @@ assert.equal(true,threw,'a.doesNotThrow is not catching type matching errors');
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;
}
});

Loading…
Cancel
Save