From 432795724aede561049fa165d6de5779839630f9 Mon Sep 17 00:00:00 2001 From: cjihrig Date: Sun, 6 Dec 2015 00:17:26 -0500 Subject: [PATCH] assert: handle class constructors in throws() Currently, if a class constructor is passed as the expected value to throws(), and a match is not received, the code falls through to the validation function case, which uses fn.prototype.call(). Class constructors must be called with new, so this throws a TypeError. This commit adds a try...catch, which handles the thrown error. --- lib/assert.js | 8 +++++++- test/parallel/test-assert.js | 16 ++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/lib/assert.js b/lib/assert.js index f8e4920cf38959..f8d8fc63da6d5e 100644 --- a/lib/assert.js +++ b/lib/assert.js @@ -278,7 +278,13 @@ function expectedException(actual, expected) { // Ignore. The instanceof check doesn't work for arrow functions. } - return expected.call({}, actual) === true; + try { + return expected.call({}, actual) === true; + } catch (e) { + // Ignore. If expected is a class constructor, an error will be thrown + } + + return false; } function _throws(shouldThrow, block, expected, message) { diff --git a/test/parallel/test-assert.js b/test/parallel/test-assert.js index 0b300e737b367d..25ba94ef6c2fc5 100644 --- a/test/parallel/test-assert.js +++ b/test/parallel/test-assert.js @@ -334,6 +334,22 @@ try { } assert.ok(threw, 'wrong constructor validation'); +// Validate that a class constructor works with throws() +threw = false; + +try { + const ClassError = class {}; + + assert.throws(() => { + throw new RangeError(); + }, ClassError); +} catch (e) { + assert(e instanceof RangeError); + threw = true; +} + +assert.ok(threw, 'wrong constructor validation'); + // use a RegExp to validate error message a.throws(makeBlock(thrower, TypeError), /test/);