Skip to content

Commit 14dc917

Browse files
committed
assert: throw when block is not a function
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 <info@bnoordhuis.nl>
1 parent 7c4a50d commit 14dc917

File tree

2 files changed

+39
-2
lines changed

2 files changed

+39
-2
lines changed

lib/assert.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -283,6 +283,10 @@ function expectedException(actual, expected) {
283283
function _throws(shouldThrow, block, expected, message) {
284284
var actual;
285285

286+
if (!util.isFunction(block)) {
287+
throw new TypeError('block must be a function');
288+
}
289+
286290
if (util.isString(expected)) {
287291
message = expected;
288292
expected = null;

test/parallel/test-assert.js

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -267,8 +267,6 @@ try {
267267
var args = (function() { return arguments; })();
268268
a.throws(makeBlock(a.deepEqual, [], args));
269269
a.throws(makeBlock(a.deepEqual, args, []));
270-
271-
console.log('All OK');
272270
assert.ok(gotError);
273271

274272

@@ -329,3 +327,38 @@ try {
329327
assert.equal(e.generatedMessage, false,
330328
'Message incorrectly marked as generated');
331329
}
330+
331+
// Verify that throws() and doesNotThrow() throw on non-function block
332+
function testBlockTypeError(method, block) {
333+
var threw = true;
334+
335+
try {
336+
method(block);
337+
threw = false;
338+
} catch (e) {
339+
assert.equal(e.toString(), 'TypeError: block must be a function');
340+
}
341+
342+
assert.ok(threw);
343+
}
344+
345+
testBlockTypeError(assert.throws, 'string');
346+
testBlockTypeError(assert.doesNotThrow, 'string');
347+
testBlockTypeError(assert.throws, 1);
348+
testBlockTypeError(assert.doesNotThrow, 1);
349+
testBlockTypeError(assert.throws, true);
350+
testBlockTypeError(assert.doesNotThrow, true);
351+
testBlockTypeError(assert.throws, false);
352+
testBlockTypeError(assert.doesNotThrow, false);
353+
testBlockTypeError(assert.throws, []);
354+
testBlockTypeError(assert.doesNotThrow, []);
355+
testBlockTypeError(assert.throws, {});
356+
testBlockTypeError(assert.doesNotThrow, {});
357+
testBlockTypeError(assert.throws, /foo/);
358+
testBlockTypeError(assert.doesNotThrow, /foo/);
359+
testBlockTypeError(assert.throws, null);
360+
testBlockTypeError(assert.doesNotThrow, null);
361+
testBlockTypeError(assert.throws, undefined);
362+
testBlockTypeError(assert.doesNotThrow, undefined);
363+
364+
console.log('All OK');

0 commit comments

Comments
 (0)