assert: add more information to AssertionErrors

This adds information about the actual thrown error to the
AssertionError's message property.

It also improves the logged error instances error name by using the
constructors name, if available.

PR-URL: https://github.com/nodejs/node/pull/28263
Reviewed-By: Rich Trott <rtrott@gmail.com>
Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
This commit is contained in:
Ruben Bridgewater committed 2019-10-01 22:56:01 +02:00
1 parent 5700cd17dd
commit 97c52ca5dc
3 files changed
+16 -5

No files matched your search

+10 -1
View File
@@ -620,8 +620,13 @@ function expectedException(actual, expected, message, fn) {
generatedMessage = true;
message = 'The error is expected to be an instance of ' +
`"${expected.name}". Received `;
// TODO: Special handle identical names.
if (isError(actual)) {
message += `"${actual.name}"`;
const name = actual.constructor && actual.constructor.name;
message += `"${name || actual.name}"`;
if (actual.message) {
message += `\n\nError message:\n\n${actual.message}`;
}
} else {
message += `"${inspect(actual, { depth: -1 })}"`;
}
@@ -636,6 +641,10 @@ function expectedException(actual, expected, message, fn) {
const name = expected.name ? `"${expected.name}" ` : '';
message = `The ${name}validation function is expected to return` +
` "true". Received ${inspect(res)}`;
if (isError(actual)) {
message += `\n\nCaught error:\n\n${actual}`;
}
}
throwError = true;
}
+2 -1
View File
@@ -73,7 +73,8 @@ const invalidThenableFunc = () => {
() => assert.rejects(Promise.reject(err), validate),
{
message: 'The "validate" validation function is expected to ' +
"return \"true\". Received 'baz'",
"return \"true\". Received 'baz'\n\nCaught error:\n\n" +
'Error: foobar',
code: 'ERR_ASSERTION',
actual: err,
expected: validate,
+4 -3
View File
@@ -133,7 +133,7 @@ assert.throws(
name: 'AssertionError',
operator: 'throws',
message: 'The error is expected to be an instance of "AssertionError". ' +
'Received "TypeError"'
'Received "TypeError"\n\nError message:\n\n[object Object]'
}
);
@@ -255,7 +255,7 @@ a.throws(() => thrower(TypeError), (err) => {
assert.strictEqual(
err.message,
'The error is expected to be an instance of "ES6Error". ' +
'Received "Error"'
'Received "AnotherErrorType"\n\nError message:\n\nfoo'
);
assert.strictEqual(err.actual, actual);
return true;
@@ -1334,7 +1334,8 @@ assert.throws(
() => assert.throws(() => { throw err; }, validate),
{
message: 'The validation function is expected to ' +
`return "true". Received ${inspect(validate())}`,
`return "true". Received ${inspect(validate())}\n\nCaught ` +
`error:\n\n${err}`,
code: 'ERR_ASSERTION',
actual: err,
expected: validate,