Skip to content

Commit 8383c4f

Browse files
bnoordhuisjasnell
authored andcommitted
assert: support arrow functions in .throws()
`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 <[email protected]> Reviewed-By: Sakthipriyan Vairamani <[email protected]>
1 parent f0f8afd commit 8383c4f

File tree

2 files changed

+13
-5
lines changed

2 files changed

+13
-5
lines changed

lib/assert.js

+9-5
Original file line numberDiff line numberDiff line change
@@ -268,13 +268,17 @@ function expectedException(actual, expected) {
268268

269269
if (Object.prototype.toString.call(expected) == '[object RegExp]') {
270270
return expected.test(actual);
271-
} else if (actual instanceof expected) {
272-
return true;
273-
} else if (expected.call({}, actual) === true) {
274-
return true;
275271
}
276272

277-
return false;
273+
try {
274+
if (actual instanceof expected) {
275+
return true;
276+
}
277+
} catch (e) {
278+
// Ignore. The instanceof check doesn't work for arrow functions.
279+
}
280+
281+
return expected.call({}, actual) === true;
278282
}
279283

280284
function _throws(shouldThrow, block, expected, message) {

test/parallel/test-assert.js

+4
Original file line numberDiff line numberDiff line change
@@ -465,4 +465,8 @@ testBlockTypeError(assert.doesNotThrow, null);
465465
testBlockTypeError(assert.throws, undefined);
466466
testBlockTypeError(assert.doesNotThrow, undefined);
467467

468+
// https://github.com/nodejs/node/issues/3275
469+
assert.throws(() => { throw 'error'; }, err => err === 'error');
470+
assert.throws(() => { throw Error(); }, err => err instanceof Error);
471+
468472
console.log('All OK');

0 commit comments

Comments
 (0)