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: #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 f96ea47 commit b35eabb

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

lib/assert.js

+6-3
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
@@ -256,6 +258,7 @@ function getActual(block) {
256258
} catch (e) {
257259
return e;
258260
}
261+
return NO_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
let details = '';
278281
if (error && error.name) {
279282
details += ` (${error.name})`;
@@ -294,7 +297,7 @@ assert.throws = function throws(block, error, message) {
294297

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

300303
if (typeof error === '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

+12
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)