diff --git a/lib/internal/assert/assertion_error.js b/lib/internal/assert/assertion_error.js index 5d8c45040af0fe..2f222a3d85ebf9 100644 --- a/lib/internal/assert/assertion_error.js +++ b/lib/internal/assert/assertion_error.js @@ -72,7 +72,11 @@ function inspectValue(val) { ); } -function createErrDiff(actual, expected, operator) { +function getErrorMessage(operator, message) { + return message || kReadableOperator[operator]; +} + +function createErrDiff(actual, expected, operator, message = '') { let other = ''; let res = ''; let end = ''; @@ -110,7 +114,7 @@ function createErrDiff(actual, expected, operator) { if ((typeof actual !== 'object' || actual === null) && (typeof expected !== 'object' || expected === null) && (actual !== 0 || expected !== 0)) { // -0 === +0 - return `${kReadableOperator[operator]}\n\n` + + return `${getErrorMessage(operator, message)}\n\n` + `${actualLines[0]} !== ${expectedLines[0]}\n`; } } else if (operator !== 'strictEqualObject') { @@ -184,8 +188,7 @@ function createErrDiff(actual, expected, operator) { let printedLines = 0; let identical = 0; - const msg = kReadableOperator[operator] + - `\n${colors.green}+ actual${colors.white} ${colors.red}- expected${colors.white}`; + const msg = `${getErrorMessage(operator, message)}\n${colors.green}+ actual${colors.white} ${colors.red}- expected${colors.white}`; const skippedMsg = ` ${colors.blue}...${colors.white} Lines skipped`; let lines = actualLines; @@ -337,7 +340,11 @@ class AssertionError extends Error { if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0; if (message != null) { - super(String(message)); + if (operator === 'deepStrictEqual' || operator === 'strictEqual') { + super(createErrDiff(actual, expected, operator, message)); + } else { + super(String(message)); + } } else { // Reset colors on each call to make sure we handle dynamically set environment // variables correct. diff --git a/test/parallel/test-assert.js b/test/parallel/test-assert.js index b5e5bb1c9b0a29..0197ebf543a3cb 100644 --- a/test/parallel/test-assert.js +++ b/test/parallel/test-assert.js @@ -391,7 +391,7 @@ test('Test assertion messages', () => { assert.throws( () => assert.strictEqual(1, 2, 'oh no'), { - message: 'oh no', + message: 'oh no\n\n1 !== 2\n', generatedMessage: false } ); @@ -1204,7 +1204,7 @@ test('Additional assert', () => { ), { actual, - message, + message: "message\n+ actual - expected\n\n+ 'foobar'\n- {\n- message: 'foobar'\n- }", operator: 'throws', generatedMessage: false } @@ -1251,6 +1251,17 @@ test('Additional assert', () => { } ); + assert.throws( + () => { + assert.deepStrictEqual({ a: true }, { a: false }, 'custom message'); + }, + { + code: 'ERR_ASSERTION', + name: 'AssertionError', + message: 'custom message\n+ actual - expected\n\n {\n+ a: true\n- a: false\n }' + } + ); + { let threw = false; try {