Skip to content

Commit

Permalink
assert: ensure .rejects() disallows sync throws
Browse files Browse the repository at this point in the history
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: #19646
Backport-PR-URL: #24019
PR-URL: #19650
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
  • Loading branch information
not-an-aardvark authored and MylesBorins committed Nov 4, 2018
1 parent 3cd4462 commit 0d241ba
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
5 changes: 4 additions & 1 deletion lib/assert.js
Expand Up @@ -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;
}
Expand Down
15 changes: 14 additions & 1 deletion test/parallel/test-assert-async.js
Expand Up @@ -13,7 +13,7 @@ common.crashOnUnhandledRejection();

(async () => {
await assert.rejects(
() => assert.fail(),
async () => assert.fail('Failed'),
common.expectsError({
code: 'ERR_ASSERTION',
type: assert.AssertionError,
Expand Down Expand Up @@ -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());

0 comments on commit 0d241ba

Please sign in to comment.