From 8d55d6bd4964c0f255b422bbbb2c5ac5e63a58d7 Mon Sep 17 00:00:00 2001 From: Dmytro Tiapukhin <53977359+eddienubes@users.noreply.github.com> Date: Sun, 16 Jun 2024 14:21:31 +0200 Subject: [PATCH] fix: toJSON recursive error serialization (fix #5848) (#5884) --- packages/utils/src/error.ts | 2 +- test/core/test/serialize.test.ts | 28 ++++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/packages/utils/src/error.ts b/packages/utils/src/error.ts index ca0605685860..ebdafeb5d56f 100644 --- a/packages/utils/src/error.ts +++ b/packages/utils/src/error.ts @@ -45,7 +45,7 @@ export function serializeError(val: any, seen = new WeakMap()): any { if (typeof val.asymmetricMatch === 'function') return `${val.toString()} ${format(val.sample)}` if (typeof val.toJSON === 'function') - return val.toJSON() + return serializeError(val.toJSON(), seen) if (seen.has(val)) return seen.get(val) diff --git a/test/core/test/serialize.test.ts b/test/core/test/serialize.test.ts index 2b29aa728b4f..af2721376d44 100644 --- a/test/core/test/serialize.test.ts +++ b/test/core/test/serialize.test.ts @@ -168,4 +168,32 @@ describe('error serialize', () => { message: 'test', }) }) + + it('should serialize when toJSON does not return JSON-compatible object', () => { + class TestClass {} + + const error = { + key: 'value', + // Still not serialized, thus second round of serialization is needed + toJSON() { + return { + key: 'value', + obj: { + fn: () => {}, + class: TestClass, + }, + } + }, + } + + const serialized = serializeError(error) + + expect(serialized).toEqual({ + key: 'value', + obj: { + fn: 'Function', + class: 'Function', + }, + }) + }) })