Skip to content

Commit

Permalink
assert: show the diff when deep comparing data with a custom message
Browse files Browse the repository at this point in the history
Fixes: #48465
  • Loading branch information
puskin94 committed Sep 4, 2024
1 parent 5949e16 commit 89cb67f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 7 deletions.
12 changes: 8 additions & 4 deletions lib/internal/assert/assertion_error.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ function inspectValue(val) {
);
}

function createErrDiff(actual, expected, operator) {
function createErrDiff(actual, expected, operator, message = '') {
let other = '';
let res = '';
let end = '';
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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.
Expand Down
17 changes: 14 additions & 3 deletions test/parallel/test-assert.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
);
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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 {
Expand Down

0 comments on commit 89cb67f

Please sign in to comment.