Skip to content

Commit

Permalink
assert: show thrown message in doesNotThrow()
Browse files Browse the repository at this point in the history
assert.doesNotThrow() should show actual error message instead
of "Got unwanted exception" which is not really helpful.

PR-URL: nodejs#12167
Reviewed-By: Anna Henningsen <[email protected]>
Reviewed-By: Yuta Hiroto <[email protected]>
Reviewed-By: James M Snell <[email protected]>
Reviewed-By: Joyee Cheung <[email protected]>
Reviewed-By: Refael Ackermann <[email protected]>
  • Loading branch information
krydos authored and refack committed Jul 9, 2017
1 parent 1b2733f commit 7011772
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
15 changes: 10 additions & 5 deletions lib/assert.js
Original file line number Diff line number Diff line change
Expand Up @@ -517,7 +517,7 @@ function tryBlock(block) {
}
}

function innerThrows(shouldThrow, block, expected, message) {
function innerThrows(shouldThrow, block, expected, message, caller) {
var details = '';

if (typeof block !== 'function') {
Expand All @@ -538,27 +538,32 @@ function innerThrows(shouldThrow, block, expected, message) {
details += ` (${expected.name})`;
}
details += message ? `: ${message}` : '.';
fail(actual, expected, `Missing expected exception${details}`, fail);
fail(actual, expected, `Missing expected exception${details}`, caller);
}
if (expected && expectedException(actual, expected) === false) {
throw actual;
}
} else if (actual !== undefined) {
if (!expected || expectedException(actual, expected)) {
details = message ? `: ${message}` : '.';
fail(actual, expected, `Got unwanted exception${details}`, fail);
fail(
actual,
expected,
`Got unwanted exception${details}\n${actual.message}`,
caller
);
}
throw actual;
}
}

// Expected to throw an error.
assert.throws = function throws(block, error, message) {
innerThrows(true, block, error, message);
innerThrows(true, block, error, message, throws);
};

assert.doesNotThrow = function doesNotThrow(block, error, message) {
innerThrows(false, block, error, message);
innerThrows(false, block, error, message, doesNotThrow);
};

assert.ifError = function ifError(err) { if (err) throw err; };
8 changes: 8 additions & 0 deletions test/parallel/test-assert.js
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,14 @@ assert.throws(() => {
}, /Got unwanted exception: user message/,
'a.doesNotThrow ignores user message');

assert.throws(() => {
assert.doesNotThrow(makeBlock(thrower, Error), 'user message');
}, /Got unwanted exception: user message\ntest/);

assert.throws(() => {
assert.doesNotThrow(makeBlock(thrower, Error));
}, /Got unwanted exception\.\ntest/);

// make sure that validating using constructor really works
{
let threw = false;
Expand Down

0 comments on commit 7011772

Please sign in to comment.