Skip to content

Commit

Permalink
assert: fix deepStrictEqual on errors when cause is not undefined
Browse files Browse the repository at this point in the history
PR-URL: #55406
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Ulises Gascón <ulisesgascongonzalez@gmail.com>
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
  • Loading branch information
geeksilva97 authored and aduh95 committed Nov 6, 2024
1 parent 7d93c0c commit 9dbb255
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
11 changes: 11 additions & 0 deletions lib/internal/assert/assertion_error.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ const {
StringPrototypeSplit,
} = primordials;

const { isError } = require('internal/util');

const { inspect } = require('internal/util/inspect');
const colors = require('internal/util/colors');
const { validateObject } = require('internal/validators');
Expand Down Expand Up @@ -47,6 +49,15 @@ function copyError(source) {
__proto__: null,
value: source.message,
});
if (source.cause !== undefined) {
let cause = source.cause;

if (isError(cause)) {
cause = copyError(cause);
}

ObjectDefineProperty(target, 'cause', { __proto__: null, value: cause });
}
return target;
}

Expand Down
39 changes: 39 additions & 0 deletions test/parallel/test-assert-deep-with-error.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
'use strict';
require('../common');
const assert = require('assert');
const { test } = require('node:test');

const defaultStartMessage = 'Expected values to be strictly deep-equal:\n' +
'+ actual - expected\n' +
'\n';

test('Handle error causes', () => {
assert.throws(() => {
assert.deepStrictEqual(new Error('a', { cause: new Error('x') }), new Error('a', { cause: new Error('y') }));
}, { message: defaultStartMessage + ' [Error: a] {\n' +
'+ [cause]: [Error: x]\n' +
'- [cause]: [Error: y]\n' +
' }\n' });

assert.throws(() => {
assert.deepStrictEqual(new Error('a'), new Error('a', { cause: new Error('y') }));
}, { message: defaultStartMessage + '+ [Error: a]\n' +
'- [Error: a] {\n' +
'- [cause]: [Error: y]\n' +
'- }\n' });

assert.throws(() => {
assert.deepStrictEqual(new Error('a'), new Error('a', { cause: { prop: 'value' } }));
}, { message: defaultStartMessage + '+ [Error: a]\n' +
'- [Error: a] {\n' +
'- [cause]: {\n' +
'- prop: \'value\'\n' +
'- }\n' +
'- }\n' });

assert.notDeepStrictEqual(new Error('a', { cause: new Error('x') }), new Error('a', { cause: new Error('y') }));
assert.notDeepStrictEqual(
new Error('a', { cause: { prop: 'value' } }),
new Error('a', { cause: { prop: 'a different value' } })
);
});

0 comments on commit 9dbb255

Please sign in to comment.