forked from vue-mini/vue-mini
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvitest.setup.ts
105 lines (93 loc) · 2.64 KB
/
vitest.setup.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import type { MockInstance } from 'vitest'
interface CustomMatchers<R = unknown> {
toHaveBeenWarned: () => R
toHaveBeenWarnedLast: () => R
toHaveBeenWarnedTimes: (n: number) => R
}
declare module 'vitest' {
interface Assertion<T = any> extends CustomMatchers<T> {}
interface AsymmetricMatchersContaining extends CustomMatchers {}
}
expect.extend({
toHaveBeenWarned(received: string) {
const passed = warn.mock.calls.some((args) => args[0].includes(received))
if (passed) {
asserted.add(received)
return {
pass: true,
message: () => `expected "${received}" not to have been warned.`,
}
}
const msgs = warn.mock.calls.map((args) => args[0]).join('\n - ')
return {
pass: false,
message: () =>
`expected "${received}" to have been warned` +
(msgs.length > 0 ?
`.\n\nActual messages:\n\n - ${msgs}`
: ` but no warning was recorded.`),
}
},
toHaveBeenWarnedLast(received: string) {
// @ts-expect-error
const passed = warn.mock.calls.at(-1)![0].includes(received)
if (passed) {
asserted.add(received)
return {
pass: true,
message: () => `expected "${received}" not to have been warned last.`,
}
}
const msgs = warn.mock.calls.map((args) => args[0]).join('\n - ')
return {
pass: false,
message: () =>
`expected "${received}" to have been warned last.\n\nActual messages:\n\n - ${msgs}`,
}
},
toHaveBeenWarnedTimes(received: string, n: number) {
let found = 0
warn.mock.calls.forEach((args) => {
if (args[0].includes(received)) {
found++
}
})
if (found === n) {
asserted.add(received)
return {
pass: true,
message: () => `expected "${received}" to have been warned ${n} times.`,
}
}
return {
pass: false,
message: () =>
`expected "${received}" to have been warned ${n} times but got ${found}.`,
}
},
})
let warn: MockInstance
const asserted = new Set<string>()
beforeEach(() => {
asserted.clear()
warn = vi.spyOn(console, 'warn')
// eslint-disable-next-line @typescript-eslint/no-empty-function
warn.mockImplementation(() => {})
})
afterEach(() => {
const assertedArray = [...asserted]
const nonAssertedWarnings = warn.mock.calls
.map((args) => args[0])
.filter(
(received: string) =>
!assertedArray.some((assertedMsg) => received.includes(assertedMsg)),
)
warn.mockRestore()
if (nonAssertedWarnings.length > 0) {
throw new Error(
`test case threw unexpected warnings:\n - ${nonAssertedWarnings.join(
'\n - ',
)}`,
)
}
})