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 <jasnell@gmail.com> Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
1 parent 3cd4462 commit 0d241ba

2 files changed

Lines changed: 18 additions & 2 deletions

File tree

‎lib/assert.js‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -722,8 +722,11 @@ async function waitForActual(block) {
722722
if(typeofblock!=='function'){
723723
thrownewerrors.ERR_INVALID_ARG_TYPE('block','Function',block);
724724
}
725+
726+
// Return a rejected promise if `block` throws synchronously.
727+
constresultPromise=block();
725728
try{
726-
awaitblock();
729+
awaitresultPromise;
727730
}catch(e){
728731
returne;
729732
}

‎test/parallel/test-assert-async.js‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ common.crashOnUnhandledRejection();
1313

1414
(async()=>{
1515
awaitassert.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+
constTHROWN_ERROR=newError();
63+
64+
awaitassert.rejects(()=>{
65+
throwTHROWN_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)