Skip to content

Commit

Permalink
assert: support arrow functions in .throws()
Browse files Browse the repository at this point in the history
`x instanceof f` where f is an arrow function throws a (spec-conforming)
"Function has non-object prototype 'undefined' in instanceof check"
exception.

Add a workaround so that it's possible to pass arrow functions as the
second argument to assert.throws().  The try/catch block is a little
jarring but swapping around the clauses in the if statements changes
the semantics too much.

Fixes: #3275
PR-URL: #3276
Reviewed-By: Michaël Zasso <mic.besace@gmail.com>
Reviewed-By: Sakthipriyan Vairamani <thechargingvolcano@gmail.com>
  • Loading branch information
bnoordhuis authored and jasnell committed Oct 10, 2015
1 parent f0f8afd commit 8383c4f
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
14 changes: 9 additions & 5 deletions lib/assert.js
Original file line number Diff line number Diff line change
Expand Up @@ -268,13 +268,17 @@ function expectedException(actual, expected) {

if (Object.prototype.toString.call(expected) == '[object RegExp]') {
return expected.test(actual);
} else if (actual instanceof expected) {
return true;
} else if (expected.call({}, actual) === true) {
return true;
}

return false;
try {
if (actual instanceof expected) {
return true;
}
} catch (e) {
// Ignore. The instanceof check doesn't work for arrow functions.
}

return expected.call({}, actual) === true;
}

function _throws(shouldThrow, block, expected, message) {
Expand Down
4 changes: 4 additions & 0 deletions test/parallel/test-assert.js
Original file line number Diff line number Diff line change
Expand Up @@ -465,4 +465,8 @@ testBlockTypeError(assert.doesNotThrow, null);
testBlockTypeError(assert.throws, undefined);
testBlockTypeError(assert.doesNotThrow, undefined);

// https://github.com/nodejs/node/issues/3275
assert.throws(() => { throw 'error'; }, err => err === 'error');
assert.throws(() => { throw Error(); }, err => err instanceof Error);

console.log('All OK');

0 comments on commit 8383c4f

Please sign in to comment.