diff --git a/lib/internal/assert/assertion_error.js b/lib/internal/assert/assertion_error.js index 5d8c45040af0fe..2cec6bb08f432f 100644 --- a/lib/internal/assert/assertion_error.js +++ b/lib/internal/assert/assertion_error.js @@ -72,7 +72,7 @@ function inspectValue(val) { ); } -function createErrDiff(actual, expected, operator) { +function createErrDiff(actual, expected, operator, message = '') { let other = ''; let res = ''; let end = ''; @@ -184,8 +184,8 @@ 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 errorMsg = message || kReadableOperator[operator]; + const msg = `${errorMsg}\n${colors.green}+ actual${colors.white} ${colors.red}- expected${colors.white}`; const skippedMsg = ` ${colors.blue}...${colors.white} Lines skipped`; let lines = actualLines; @@ -337,7 +337,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..5d9ab39152a200 100644 --- a/test/parallel/test-assert.js +++ b/test/parallel/test-assert.js @@ -389,9 +389,9 @@ test('Test assertion messages', () => { ); assert.throws( - () => assert.strictEqual(1, 2, 'oh no'), + () => assert.strictEqual(1, 2, 'Expected values to be strictly equal:\n\n1 !== 2\n'), { - message: 'oh no', + message: 'Expected values to be strictly equal:\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 {