Skip to content

Commit

Permalink
fix: use toJSON for error serialization (#5526)
Browse files Browse the repository at this point in the history
  • Loading branch information
hi-ogawa authored May 2, 2024
1 parent c9883f3 commit 19a21e4
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 3 deletions.
2 changes: 2 additions & 0 deletions packages/utils/src/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
5 changes: 5 additions & 0 deletions test/reporters/fixtures/error-to-json.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { test } from "vitest";

test("error serialization with toJSON", () => {
throw Object.assign(new Error("hello"), { date: new Date(0) })
})
3 changes: 0 additions & 3 deletions test/reporters/tests/__snapshots__/html.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ exports[`html reporter > resolves to "failing" status for test file "json-fail"
"errors": [
{
"actual": "2",
"constructor": "Function<AssertionError>",
"diff": "- Expected
+ Received
Expand All @@ -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<anonymous>",
"toString": "Function<toString>",
},
],
"hooks": {
Expand Down
7 changes: 7 additions & 0 deletions test/reporters/tests/error-to-json.test.ts
Original file line number Diff line number Diff line change
@@ -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' }`)
})

0 comments on commit 19a21e4

Please sign in to comment.