Skip to content

Commit 71203f5

Browse files
bnoordhuisjasnell
authored andcommitted
lib: handle throw undefined in assert.throws()
And make `assert.doesNotThrow()` handle it as well. PR-URL: #18029 Fixes: #18027 Reviewed-By: Anna Henningsen <anna@addaleax.net> Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de> Reviewed-By: Khaidi Chu <i@2333.moe> Reviewed-By: Tiancheng "Timothy" Gu <timothygu99@gmail.com> Reviewed-By: Daniel Bevenius <daniel.bevenius@gmail.com> Reviewed-By: Colin Ihrig <cjihrig@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com>
1 parent 7a18f09 commit 71203f5

2 files changed

Lines changed: 18 additions & 3 deletions

File tree

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
const assert = module.exports = ok;
3333

34+
const NO_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
@@ -253,6 +255,7 @@ function getActual(block) {
253255
} catch (e) {
254256
return e;
255257
}
258+
return NO_EXCEPTION_SENTINEL;
256259
}
257260

258261
// Expected to throw an error.
@@ -270,7 +273,7 @@ assert.throws = function throws(block, error, message) {
270273
error = null;
271274
}
272275

273-
if (actual === undefined) {
276+
if (actual === NO_EXCEPTION_SENTINEL) {
274277
let details = '';
275278
if (error && error.name) {
276279
details += ` (${error.name})`;
@@ -291,7 +294,7 @@ assert.throws = function throws(block, error, message) {
291294

292295
assert.doesNotThrow = function doesNotThrow(block, error, message) {
293296
const actual = getActual(block);
294-
if (actual === undefined)
297+
if (actual === NO_EXCEPTION_SENTINEL)
295298
return;
296299

297300
if (typeof error === 'string') {
@@ -305,7 +308,7 @@ assert.doesNotThrow = function doesNotThrow(block, error, message) {
305308
actual,
306309
expected: error,
307310
operator: 'doesNotThrow',
308-
message: `Got unwanted exception${details}\n${actual.message}`,
311+
message: `Got unwanted exception${details}\n${actual && actual.message}`,
309312
stackStartFn: doesNotThrow
310313
});
311314
}

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(() => { throw undefined; }, /undefined/);
863+
common.expectsError(
864+
// eslint-disable-next-line no-throw-literal
865+
() => assert.doesNotThrow(() => { throw undefined; }),
866+
{
867+
type: assert.AssertionError,
868+
code: 'ERR_ASSERTION',
869+
message: 'Got unwanted exception.\nundefined'
870+
}
871+
);
860872
}

0 commit comments

Comments
 (0)