diff --git a/lib/assert.js b/lib/assert.js index 57d45ed2eba541..0762ec75074cf6 100644 --- a/lib/assert.js +++ b/lib/assert.js @@ -31,6 +31,8 @@ const { inspect } = require('util'); const assert = module.exports = ok; +const NO_EXCEPTION_SENTINEL = {}; + // All of the following functions must throw an AssertionError // when a corresponding condition is not met, with a message that // may be undefined if not provided. All assertion methods provide @@ -253,6 +255,7 @@ function getActual(block) { } catch (e) { return e; } + return NO_EXCEPTION_SENTINEL; } // Expected to throw an error. @@ -270,7 +273,7 @@ assert.throws = function throws(block, error, message) { error = null; } - if (actual === undefined) { + if (actual === NO_EXCEPTION_SENTINEL) { let details = ''; if (error && error.name) { details += ` (${error.name})`; @@ -291,7 +294,7 @@ assert.throws = function throws(block, error, message) { assert.doesNotThrow = function doesNotThrow(block, error, message) { const actual = getActual(block); - if (actual === undefined) + if (actual === NO_EXCEPTION_SENTINEL) return; if (typeof error === 'string') { @@ -305,7 +308,7 @@ assert.doesNotThrow = function doesNotThrow(block, error, message) { actual, expected: error, operator: 'doesNotThrow', - message: `Got unwanted exception${details}\n${actual.message}`, + message: `Got unwanted exception${details}\n${actual && actual.message}`, stackStartFn: doesNotThrow }); } diff --git a/test/parallel/test-assert.js b/test/parallel/test-assert.js index 5e76a0a8fc2988..4cab6c691a4317 100644 --- a/test/parallel/test-assert.js +++ b/test/parallel/test-assert.js @@ -857,4 +857,16 @@ common.expectsError( message: "message: expected '', not 'foo'" } ); + + // eslint-disable-next-line no-throw-literal + assert.throws(() => { throw undefined; }, /undefined/); + common.expectsError( + // eslint-disable-next-line no-throw-literal + () => assert.doesNotThrow(() => { throw undefined; }), + { + type: assert.AssertionError, + code: 'ERR_ASSERTION', + message: 'Got unwanted exception.\nundefined' + } + ); }