From 0d241ba3856d25fb0a4e1732cf61acc6fba54fbb 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 Backport-PR-URL: https://github.com/nodejs/node/pull/24019 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 545f76bef4b6a3..594a5acfbde1e3 100644 --- a/lib/assert.js +++ b/lib/assert.js @@ -722,8 +722,11 @@ async function waitForActual(block) { if (typeof block !== 'function') { throw new errors.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..c397a4db081d49 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('Failed'), 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());