Skip to content

Commit b35eabb

Browse files
bnoordhuisMylesBorins
authored andcommitted
lib: handle throw undefined in assert.throws()
And make `assert.doesNotThrow()` handle it as well. Backport-PR-URL: #19230 PR-URL: #18029Fixes: #18027 Reviewed-By: Anna Henningsen <[email protected]> Reviewed-By: Ruben Bridgewater <[email protected]> Reviewed-By: Khaidi Chu <[email protected]> Reviewed-By: Tiancheng "Timothy" Gu <[email protected]> Reviewed-By: Daniel Bevenius <[email protected]> Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: James M Snell <[email protected]>
1 parent f96ea47 commit b35eabb

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

‎lib/assert.js‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@ const{inspect } = require('util');
3131

3232
constassert=module.exports=ok;
3333

34+
constNO_EXCEPTION_SENTINEL={};
35+
3436
// All of the following functions must throw an AssertionError
3537
// when a corresponding condition is not met, with a message that
3638
// may be undefined if not provided. All assertion methods provide
@@ -256,6 +258,7 @@ function getActual(block){
256258
}catch(e){
257259
returne;
258260
}
261+
returnNO_EXCEPTION_SENTINEL;
259262
}
260263

261264
// Expected to throw an error.
@@ -273,7 +276,7 @@ assert.throws = function throws(block, error, message){
273276
error=null;
274277
}
275278

276-
if(actual===undefined){
279+
if(actual===NO_EXCEPTION_SENTINEL){
277280
letdetails='';
278281
if(error&&error.name){
279282
details+=` (${error.name})`;
@@ -294,7 +297,7 @@ assert.throws = function throws(block, error, message){
294297

295298
assert.doesNotThrow=functiondoesNotThrow(block,error,message){
296299
constactual=getActual(block);
297-
if(actual===undefined)
300+
if(actual===NO_EXCEPTION_SENTINEL)
298301
return;
299302

300303
if(typeoferror==='string'){
@@ -308,7 +311,7 @@ assert.doesNotThrow = function doesNotThrow(block, error, message){
308311
actual,
309312
expected: error,
310313
operator: 'doesNotThrow',
311-
message: `Got unwanted exception${details}\n${actual.message}`,
314+
message: `Got unwanted exception${details}\n${actual&&actual.message}`,
312315
stackStartFn: doesNotThrow
313316
});
314317
}

‎test/parallel/test-assert.js‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -857,4 +857,16 @@ common.expectsError(
857857
message: "message: expected '', not 'foo'"
858858
}
859859
);
860+
861+
// eslint-disable-next-line no-throw-literal
862+
assert.throws(()=>{throwundefined;},/undefined/);
863+
common.expectsError(
864+
// eslint-disable-next-line no-throw-literal
865+
()=>assert.doesNotThrow(()=>{throwundefined;}),
866+
{
867+
type: assert.AssertionError,
868+
code: 'ERR_ASSERTION',
869+
message: 'Got unwanted exception.\nundefined'
870+
}
871+
);
860872
}

0 commit comments

Comments
(0)