Skip to content

Commit

Permalink
lib: handle throw undefined in assert.throws()
Browse files Browse the repository at this point in the history
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>
  • Loading branch information
bnoordhuis authored and MylesBorins committed Mar 20, 2018
1 parent f96ea47 commit b35eabb
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
9 changes: 6 additions & 3 deletions lib/assert.js
Expand Up @@ -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
Expand Down Expand Up @@ -256,6 +258,7 @@ function getActual(block) {
} catch (e) {
return e;
}
return NO_EXCEPTION_SENTINEL;
}

// Expected to throw an error.
Expand All @@ -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})`;
Expand All @@ -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') {
Expand All @@ -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
});
}
Expand Down
12 changes: 12 additions & 0 deletions test/parallel/test-assert.js
Expand Up @@ -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'
}
);
}

0 comments on commit b35eabb

Please sign in to comment.