From b35eabb83771aab59dc9fdff33df8a06d98598c3 Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Sun, 7 Jan 2018 23:17:29 +0100 Subject: [PATCH] lib: handle `throw undefined` in assert.throws() And make `assert.doesNotThrow()` handle it as well. Backport-PR-URL: https://github.com/nodejs/node/pull/19230 PR-URL: https://github.com/nodejs/node/pull/18029 Fixes: https://github.com/nodejs/node/issues/18027 Reviewed-By: Anna Henningsen Reviewed-By: Ruben Bridgewater Reviewed-By: Khaidi Chu Reviewed-By: Tiancheng "Timothy" Gu Reviewed-By: Daniel Bevenius Reviewed-By: Colin Ihrig Reviewed-By: James M Snell --- lib/assert.js | 9 ++++++--- test/parallel/test-assert.js | 12 ++++++++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/lib/assert.js b/lib/assert.js index 05daf6d05ee55a..c3570afeb38a3a 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 @@ -256,6 +258,7 @@ function getActual(block) { } catch (e) { return e; } + return NO_EXCEPTION_SENTINEL; } // Expected to throw an error. @@ -273,7 +276,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})`; @@ -294,7 +297,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') { @@ -308,7 +311,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 b2debe1d8001ac..462c01425dab5b 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' + } + ); }