assert: support arrow functions in .throws()
authorBen Noordhuis <info@bnoordhuis.nl>
Thu, 8 Oct 2015 10:25:03 +0000 (12:25 +0200)
committerJames M Snell <jasnell@gmail.com>
Sat, 10 Oct 2015 17:49:54 +0000 (10:49 -0700)
`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: https://github.com/nodejs/node/issues/3275
PR-URL: https://github.com/nodejs/node/pull/3276
Reviewed-By: Michaƫl Zasso <mic.besace@gmail.com>
Reviewed-By: Sakthipriyan Vairamani <thechargingvolcano@gmail.com>
lib/assert.js
test/parallel/test-assert.js

index ea142ed..6b99098 100644 (file)
@@ -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) {
index ce84eab..ce19462 100644 (file)
@@ -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');