Skip to content

Commit 0d241ba

Browse files
not-an-aardvarkMylesBorins
authored andcommitted
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: #19646 Backport-PR-URL: #24019 PR-URL: #19650 Reviewed-By: James M Snell <[email protected]> Reviewed-By: Ruben Bridgewater <[email protected]>
1 parent 3cd4462 commit 0d241ba

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

lib/assert.js

+4-1
Original file line numberDiff line numberDiff line change
@@ -722,8 +722,11 @@ async function waitForActual(block) {
722722
if (typeof block !== 'function') {
723723
throw new errors.ERR_INVALID_ARG_TYPE('block', 'Function', block);
724724
}
725+
726+
// Return a rejected promise if `block` throws synchronously.
727+
const resultPromise = block();
725728
try {
726-
await block();
729+
await resultPromise;
727730
} catch (e) {
728731
return e;
729732
}

test/parallel/test-assert-async.js

+14-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ common.crashOnUnhandledRejection();
1313

1414
(async () => {
1515
await assert.rejects(
16-
() => assert.fail(),
16+
async () => assert.fail('Failed'),
1717
common.expectsError({
1818
code: 'ERR_ASSERTION',
1919
type: assert.AssertionError,
@@ -57,4 +57,17 @@ common.crashOnUnhandledRejection();
5757
}
5858
);
5959
}
60+
61+
{
62+
const THROWN_ERROR = new Error();
63+
64+
await assert.rejects(() => {
65+
throw THROWN_ERROR;
66+
}).then(common.mustNotCall())
67+
.catch(
68+
common.mustCall((err) => {
69+
assert.strictEqual(err, THROWN_ERROR);
70+
})
71+
);
72+
}
6073
})().then(common.mustCall());

0 commit comments

Comments
 (0)