From ace3f169172d1f2d9e72707ec949b802f09d47d1 Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Fri, 14 Jun 2019 00:24:31 +0200 Subject: 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 Reviewed-By: Benjamin Gruenbaum Reviewed-By: James M Snell --- lib/assert.js | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) (limited to 'lib') 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. -- cgit v1.2.3