Skip to content

Commit

Permalink
assert: throw when block is not a function
Browse files Browse the repository at this point in the history
Currently, anything passed as the block argument to throws()
and doesNotThrow() is interpreted as a function, which can
lead to unexpected results. This commit checks the type of
block, and throws a TypeError if it is not a function.

Fixes: #275
PR-URL: #308
Reviewed-By: Ben Noordhuis <[email protected]>
  • Loading branch information
cjihrig committed Jan 12, 2015
1 parent 7c4a50d commit 14dc917
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
4 changes: 4 additions & 0 deletions lib/assert.js
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,10 @@ function expectedException(actual, expected) {
function _throws(shouldThrow, block, expected, message) {
var actual;

if (!util.isFunction(block)) {
throw new TypeError('block must be a function');
}

if (util.isString(expected)) {
message = expected;
expected = null;
Expand Down
37 changes: 35 additions & 2 deletions test/parallel/test-assert.js
Original file line number Diff line number Diff line change
Expand Up @@ -267,8 +267,6 @@ try {
var args = (function() { return arguments; })();
a.throws(makeBlock(a.deepEqual, [], args));
a.throws(makeBlock(a.deepEqual, args, []));

console.log('All OK');
assert.ok(gotError);


Expand Down Expand Up @@ -329,3 +327,38 @@ try {
assert.equal(e.generatedMessage, false,
'Message incorrectly marked as generated');
}

// Verify that throws() and doesNotThrow() throw on non-function block
function testBlockTypeError(method, block) {
var threw = true;

try {
method(block);
threw = false;
} catch (e) {
assert.equal(e.toString(), 'TypeError: block must be a function');
}

assert.ok(threw);
}

testBlockTypeError(assert.throws, 'string');
testBlockTypeError(assert.doesNotThrow, 'string');
testBlockTypeError(assert.throws, 1);
testBlockTypeError(assert.doesNotThrow, 1);
testBlockTypeError(assert.throws, true);
testBlockTypeError(assert.doesNotThrow, true);
testBlockTypeError(assert.throws, false);
testBlockTypeError(assert.doesNotThrow, false);
testBlockTypeError(assert.throws, []);
testBlockTypeError(assert.doesNotThrow, []);
testBlockTypeError(assert.throws, {});
testBlockTypeError(assert.doesNotThrow, {});
testBlockTypeError(assert.throws, /foo/);
testBlockTypeError(assert.doesNotThrow, /foo/);
testBlockTypeError(assert.throws, null);
testBlockTypeError(assert.doesNotThrow, null);
testBlockTypeError(assert.throws, undefined);
testBlockTypeError(assert.doesNotThrow, undefined);

console.log('All OK');

0 comments on commit 14dc917

Please sign in to comment.