diff --git a/packages/utils/src/error.ts b/packages/utils/src/error.ts index 9d6f5b548677..a79a5cef937d 100644 --- a/packages/utils/src/error.ts +++ b/packages/utils/src/error.ts @@ -44,6 +44,8 @@ export function serializeError(val: any, seen = new WeakMap()): any { return val.tagName if (typeof val.asymmetricMatch === 'function') return `${val.toString()} ${format(val.sample)}` + if (typeof val.toJSON === 'function') + return val.toJSON() if (seen.has(val)) return seen.get(val) diff --git a/test/reporters/fixtures/error-to-json.test.ts b/test/reporters/fixtures/error-to-json.test.ts new file mode 100644 index 000000000000..ecad5f1323f0 --- /dev/null +++ b/test/reporters/fixtures/error-to-json.test.ts @@ -0,0 +1,5 @@ +import { test } from "vitest"; + +test("error serialization with toJSON", () => { + throw Object.assign(new Error("hello"), { date: new Date(0) }) +}) diff --git a/test/reporters/tests/__snapshots__/html.test.ts.snap b/test/reporters/tests/__snapshots__/html.test.ts.snap index 935f8ce63f72..15110447cb09 100644 --- a/test/reporters/tests/__snapshots__/html.test.ts.snap +++ b/test/reporters/tests/__snapshots__/html.test.ts.snap @@ -45,7 +45,6 @@ exports[`html reporter > resolves to "failing" status for test file "json-fail" "errors": [ { "actual": "2", - "constructor": "Function", "diff": "- Expected + Received @@ -59,8 +58,6 @@ exports[`html reporter > resolves to "failing" status for test file "json-fail" "showDiff": true, "stack": "AssertionError: expected 2 to deeply equal 1", "stackStr": "AssertionError: expected 2 to deeply equal 1", - "toJSON": "Function", - "toString": "Function", }, ], "hooks": { diff --git a/test/reporters/tests/error-to-json.test.ts b/test/reporters/tests/error-to-json.test.ts new file mode 100644 index 000000000000..8f74e5e0656a --- /dev/null +++ b/test/reporters/tests/error-to-json.test.ts @@ -0,0 +1,7 @@ +import { expect, test } from 'vitest' +import { runVitest } from '../../test-utils' + +test('should print logs correctly', async () => { + const result = await runVitest({ root: './fixtures' }, ['error-to-json.test.ts']) + expect(result.stderr).toContain(`Serialized Error: { date: '1970-01-01T00:00:00.000Z' }`) +})