Skip to content

Commit 75d2d1e

Browse files
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
1 parent 4774af1 commit 75d2d1e

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
@@ -451,8 +451,11 @@ async function waitForActual(block) {
451451
if (typeof block !== 'function') {
452452
throw new ERR_INVALID_ARG_TYPE('block', 'Function', block);
453453
}
454+
455+
// Return a rejected promise if `block` throws synchronously.
456+
const resultPromise = block();
454457
try {
455-
await block();
458+
await resultPromise;
456459
} catch (e) {
457460
return e;
458461
}

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(),
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)