assert: special handle identical error names in instance checks

This makes sure that using `assert.throws()` or `assert.rejects()`
in combination with Error classes log appropriate error messages
in case the expected and received constructor name are identical
but not part of the same prototype chain.

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 2019-06-15 13:54:50 +02:00
parent 97c52ca5dc
commit 48d1ea5e7f
No known key found for this signature in database
GPG Key ID: F07496B3EB3C1762
2 changed files with 22 additions and 3 deletions

View File

@ -620,10 +620,14 @@ 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)) {
const name = actual.constructor && actual.constructor.name;
message += `"${name || actual.name}"`;
const name = actual.constructor && actual.constructor.name ||
actual.name;
if (expected.name === name) {
message += 'an error with identical name but a different prototype.';
} else {
message += `"${name}"`;
}
if (actual.message) {
message += `\n\nError message:\n\n${actual.message}`;
}

View File

@ -25,6 +25,7 @@
const common = require('../common');
const assert = require('assert');
const { inspect } = require('util');
const vm = require('vm');
const { internalBinding } = require('internal/test/binding');
const a = assert;
@ -1344,3 +1345,17 @@ assert.throws(
}
);
}
assert.throws(
() => {
const script = new vm.Script('new RangeError("foobar");');
const context = vm.createContext();
const err = script.runInContext(context);
assert.throws(() => { throw err; }, RangeError);
},
{
message: 'The error is expected to be an instance of "RangeError". ' +
'Received an error with identical name but a different ' +
'prototype.\n\nError message:\n\nfoobar'
}
);