Skip to content

Commit 19a21e4

Browse files
authored
fix: use toJSON for error serialization (#5526)
1 parent c9883f3 commit 19a21e4

File tree

4 files changed

+14
-3
lines changed

4 files changed

+14
-3
lines changed

packages/utils/src/error.ts

+2
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,8 @@ export function serializeError(val: any, seen = new WeakMap()): any {
4444
return val.tagName
4545
if (typeof val.asymmetricMatch === 'function')
4646
return `${val.toString()} ${format(val.sample)}`
47+
if (typeof val.toJSON === 'function')
48+
return val.toJSON()
4749

4850
if (seen.has(val))
4951
return seen.get(val)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import { test } from "vitest";
2+
3+
test("error serialization with toJSON", () => {
4+
throw Object.assign(new Error("hello"), { date: new Date(0) })
5+
})

test/reporters/tests/__snapshots__/html.test.ts.snap

-3
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,6 @@ exports[`html reporter > resolves to "failing" status for test file "json-fail"
4545
"errors": [
4646
{
4747
"actual": "2",
48-
"constructor": "Function<AssertionError>",
4948
"diff": "- Expected
5049
+ Received
5150
@@ -59,8 +58,6 @@ exports[`html reporter > resolves to "failing" status for test file "json-fail"
5958
"showDiff": true,
6059
"stack": "AssertionError: expected 2 to deeply equal 1",
6160
"stackStr": "AssertionError: expected 2 to deeply equal 1",
62-
"toJSON": "Function<anonymous>",
63-
"toString": "Function<toString>",
6461
},
6562
],
6663
"hooks": {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import { expect, test } from 'vitest'
2+
import { runVitest } from '../../test-utils'
3+
4+
test('should print logs correctly', async () => {
5+
const result = await runVitest({ root: './fixtures' }, ['error-to-json.test.ts'])
6+
expect(result.stderr).toContain(`Serialized Error: { date: '1970-01-01T00:00:00.000Z' }`)
7+
})

0 commit comments

Comments
 (0)