diff options
author | Ruben Bridgewater <ruben@bridgewater.de> | 2019-06-14 00:24:31 +0200 |
---|---|---|
committer | Ruben Bridgewater <ruben@bridgewater.de> | 2019-10-01 22:55:07 +0200 |
commit | ace3f169172d1f2d9e72707ec949b802f09d47d1 (patch) | |
tree | 18c502f83e7abe74f27148e98df7b8f2b9a2eaa8 /lib | |
parent | eb05d6881521a969ad605b137e0a06847dd01971 (diff) | |
download | node-new-ace3f169172d1f2d9e72707ec949b802f09d47d1.tar.gz |
assert: improve class instance errors
This improves `assert.throws()` and `assert.rejects()` in case error
classes are used as validation for the expected error.
In case of a failure it will now throw an `AssertionError` instead
of the received error if the check fails. That error has the received
error as actual property and the expected property is set to the
expected error class.
The error message should help users to identify the problem faster
than before by providing extra context what went wrong.
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>
Diffstat (limited to 'lib')
-rw-r--r-- | lib/assert.js | 27 |
1 files changed, 24 insertions, 3 deletions
diff --git a/lib/assert.js b/lib/assert.js index a1b22d3e46..035a7e1746 100644 --- a/lib/assert.js +++ b/lib/assert.js @@ -20,7 +20,7 @@ 'use strict'; -const { Object } = primordials; +const { Object, ObjectPrototype } = primordials; const { Buffer } = require('buffer'); const { codes: { @@ -36,6 +36,7 @@ const { inspect } = require('internal/util/inspect'); const { isPromise, isRegExp } = require('internal/util/types'); const { EOL } = require('internal/constants'); const { NativeModule } = require('internal/bootstrap/loaders'); +const { isError } = require('internal/util'); const errorCache = new Map(); @@ -561,6 +562,8 @@ function compareExceptionKey(actual, expected, key, message, keys, fn) { } function expectedException(actual, expected, message, fn) { + let generatedMessage = false; + if (typeof expected !== 'function') { // Handle regular expressions. if (isRegExp(expected)) { @@ -618,8 +621,26 @@ function expectedException(actual, expected, message, fn) { if (expected.prototype !== undefined && actual instanceof expected) { return; } - if (Error.isPrototypeOf(expected)) { - throw actual; + if (ObjectPrototype.isPrototypeOf(Error, expected)) { + if (!message) { + generatedMessage = true; + message = 'The error is expected to be an instance of ' + + `"${expected.name}". Received `; + if (isError(actual)) { + message += `"${actual.name}"`; + } else { + message += `"${inspect(actual, { depth: -1 })}"`; + } + } + const err = new AssertionError({ + actual, + expected, + message, + operator: fn.name, + stackStartFn: fn + }); + err.generatedMessage = generatedMessage; + throw err; } // Check validation functions return value. |