-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
snapshot-custom-serializer.test.ts
88 lines (78 loc) · 1.92 KB
/
snapshot-custom-serializer.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import { expect, test } from 'vitest'
test('basic', () => {
// example from docs/guide/snapshot.md
const bar = {
foo: {
x: 1,
y: 2,
},
}
// without custom serializer
expect(bar).toMatchInlineSnapshot(`
{
"foo": {
"x": 1,
"y": 2,
},
}
`)
// with custom serializer
expect.addSnapshotSerializer({
serialize(val, config, indentation, depth, refs, printer) {
return `Pretty foo: ${printer(
val.foo,
config,
indentation,
depth,
refs,
)}`
},
test(val) {
return val && Object.prototype.hasOwnProperty.call(val, 'foo')
},
})
expect(bar).toMatchInlineSnapshot(`
Pretty foo: {
"x": 1,
"y": 2,
}
`)
})
test('throwning snapshot', () => {
// example from https://github.com/vitest-dev/vitest/issues/3655
class ErrorWithDetails extends Error {
readonly details: unknown
constructor(message: string, options: ErrorOptions & { details: unknown }) {
super(message, options)
this.details = options.details
}
}
// without custom serializer
const error = new ErrorWithDetails('some-error', {
details: 'some-detail',
})
expect(error).toMatchInlineSnapshot(`[Error: some-error]`)
expect(() => {
throw error
}).toThrowErrorMatchingInlineSnapshot(`[Error: some-error]`)
// with custom serializer
expect.addSnapshotSerializer({
serialize(val, config, indentation, depth, refs, printer) {
const error = val as ErrorWithDetails
return `Pretty ${error.message}: ${printer(
error.details,
config,
indentation,
depth,
refs,
)}`
},
test(val) {
return val && val instanceof ErrorWithDetails
},
})
expect(error).toMatchInlineSnapshot(`Pretty some-error: "some-detail"`)
expect(() => {
throw error
}).toThrowErrorMatchingInlineSnapshot(`Pretty some-error: "some-detail"`)
})