From fdb35d89605de642f316563cd552f930e06ac306 Mon Sep 17 00:00:00 2001 From: Teddy Katz Date: Wed, 28 Mar 2018 01:21:31 -0400 Subject: [PATCH] assert: ensure .rejects() disallows sync throws This updates `assert.rejects()` to disallow any errors that are thrown synchronously from the given function. Previously, throwing an error would cause the same behavior as returning a rejected Promise. Fixes: https://github.com/nodejs/node/issues/19646 PR-URL: https://github.com/nodejs/node/pull/19650 Reviewed-By: James M Snell Reviewed-By: Ruben Bridgewater --- lib/assert.js | 5 ++++- test/parallel/test-assert-async.js | 15 ++++++++++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/lib/assert.js b/lib/assert.js index 2fc3cf33e80a18..9c900fcaf32055 100644 --- a/lib/assert.js +++ b/lib/assert.js @@ -451,8 +451,11 @@ async function waitForActual(block) { if (typeof block !== 'function') { throw new ERR_INVALID_ARG_TYPE('block', 'Function', block); } + + // Return a rejected promise if `block` throws synchronously. + const resultPromise = block(); try { - await block(); + await resultPromise; } catch (e) { return e; } diff --git a/test/parallel/test-assert-async.js b/test/parallel/test-assert-async.js index ab03a53cd302c7..b6b744c9b1e3ae 100644 --- a/test/parallel/test-assert-async.js +++ b/test/parallel/test-assert-async.js @@ -13,7 +13,7 @@ common.crashOnUnhandledRejection(); (async () => { await assert.rejects( - () => assert.fail(), + async () => assert.fail(), common.expectsError({ code: 'ERR_ASSERTION', type: assert.AssertionError, @@ -57,4 +57,17 @@ common.crashOnUnhandledRejection(); } ); } + + { + const THROWN_ERROR = new Error(); + + await assert.rejects(() => { + throw THROWN_ERROR; + }).then(common.mustNotCall()) + .catch( + common.mustCall((err) => { + assert.strictEqual(err, THROWN_ERROR); + }) + ); + } })().then(common.mustCall());