Skip to content

Commit

Permalink
assert: special handle identical error names in instance checks
Browse files Browse the repository at this point in the history
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: #28263
Reviewed-By: Rich Trott <[email protected]>
Reviewed-By: Benjamin Gruenbaum <[email protected]>
Reviewed-By: James M Snell <[email protected]>
  • Loading branch information
BridgeAR committed Oct 1, 2019
1 parent 97c52ca commit 48d1ea5
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
10 changes: 7 additions & 3 deletions lib/assert.js
Original file line number Diff line number Diff line change
Expand Up @@ -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}`;
}
Expand Down
15 changes: 15 additions & 0 deletions test/parallel/test-assert.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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'
}
);

0 comments on commit 48d1ea5

Please sign in to comment.