-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathvitest.setup.ts
More file actions
283 lines (257 loc) · 7.76 KB
/
vitest.setup.ts
File metadata and controls
283 lines (257 loc) · 7.76 KB
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
import React from 'react'
import { webcrypto } from 'node:crypto'
import { afterAll, afterEach, beforeAll, vi } from 'vitest'
import { cleanup } from '@testing-library/react'
import '@testing-library/jest-dom/vitest'
import { server } from './src/test-utils/server'
type TestRouterOverrides = Partial<{
push: (...args: any[]) => any
replace: (...args: any[]) => any
prefetch: (...args: any[]) => any
back: (...args: any[]) => any
forward: (...args: any[]) => any
refresh: (...args: any[]) => any
query: Record<string, any>
pathname: string
asPath: string
isReady: boolean
}>
type TestAuthOverrides = Partial<{
isLoading: boolean
isAuthenticated: boolean
user: any
error: any
}>
declare global {
// eslint-disable-next-line no-var
var __TEST_ROUTER__: TestRouterOverrides | undefined
// eslint-disable-next-line no-var
var __TEST_AUTH__: TestAuthOverrides | undefined
// eslint-disable-next-line no-var
var __TEST_PATHNAME__: string | undefined
// eslint-disable-next-line no-var
var __TEST_SEARCH_PARAMS__: URLSearchParams | undefined
}
// Ensure WebCrypto is available for utilities that use crypto.subtle.
if (!globalThis.crypto) {
;(globalThis as unknown as { crypto: Crypto }).crypto = webcrypto as Crypto
}
// Normalize relative fetch URLs (e.g. "/api/..." or "../api/...") so Node's fetch accepts them.
const nativeFetch = globalThis.fetch
globalThis.fetch = (input: RequestInfo | URL, init?: RequestInit) => {
if (typeof input === 'string') {
return nativeFetch(new URL(input, 'http://localhost'), init)
}
return nativeFetch(input, init)
}
// JSDOM misses a few browser APIs used by UI libs (e.g. next-themes).
if (typeof window !== 'undefined') {
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: (query: string) => ({
media: query,
matches: false,
onchange: null,
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
addListener: vi.fn(),
removeListener: vi.fn(),
dispatchEvent: vi.fn(),
}),
})
window.scrollTo = vi.fn()
// Some UI components copy text to clipboard.
if (!('clipboard' in navigator)) {
Object.defineProperty(navigator, 'clipboard', {
value: { writeText: vi.fn(() => Promise.resolve()) },
configurable: true,
})
} else if (!(navigator as any).clipboard?.writeText) {
;(navigator as any).clipboard = {
writeText: vi.fn(() => Promise.resolve()),
}
} else {
;(navigator as any).clipboard.writeText = vi.fn(() => Promise.resolve())
}
}
// JSDOM doesn't implement Element.scrollTo; several components (chat auto-scroll) call it directly.
if (typeof window !== 'undefined' && typeof HTMLElement !== 'undefined') {
if (!('scrollTo' in HTMLElement.prototype)) {
;(HTMLElement.prototype as any).scrollTo = vi.fn()
}
if (!('scrollIntoView' in HTMLElement.prototype)) {
;(HTMLElement.prototype as any).scrollIntoView = vi.fn()
}
}
// Mantine uses ResizeObserver in various components (SegmentedControl, charts, etc.).
if (typeof window !== 'undefined' && !('ResizeObserver' in window)) {
class ResizeObserver {
observe() {}
unobserve() {}
disconnect() {}
}
;(globalThis as unknown as { ResizeObserver: any }).ResizeObserver =
ResizeObserver as any
}
// Some components use IntersectionObserver for visibility/scroll tracking.
if (typeof window !== 'undefined' && !('IntersectionObserver' in window)) {
class IntersectionObserver {
constructor(_callback: any, _options?: any) {}
observe() {}
unobserve() {}
disconnect() {}
takeRecords() {
return []
}
}
;(
globalThis as unknown as { IntersectionObserver: any }
).IntersectionObserver = IntersectionObserver as any
}
// JSDOM doesn't implement URL.createObjectURL/revokeObjectURL by default.
if (typeof URL !== 'undefined') {
if (!('createObjectURL' in URL)) {
;(
URL as unknown as { createObjectURL: (obj: any) => string }
).createObjectURL = vi.fn(() => 'blob:mock')
}
if (!('revokeObjectURL' in URL)) {
;(
URL as unknown as { revokeObjectURL: (url: string) => void }
).revokeObjectURL = vi.fn()
}
}
// JSDOM's CSS/selector engine can throw on certain selectors emitted by UI libs / CSS tooling
// (e.g. `:scope` or escaped Tailwind variants). Browsers ignore these safely; tests shouldn't crash.
if (typeof window !== 'undefined' && typeof Element !== 'undefined') {
const nativeQuerySelector = Element.prototype.querySelector
const nativeQuerySelectorAll = Element.prototype.querySelectorAll
Element.prototype.querySelector = function (selectors: string) {
try {
return nativeQuerySelector.call(this, selectors)
} catch (err: any) {
if (err?.name === 'SyntaxError') return null
throw err
}
}
Element.prototype.querySelectorAll = function (selectors: string) {
try {
return nativeQuerySelectorAll.call(this, selectors)
} catch (err: any) {
if (err?.name === 'SyntaxError')
return document.createDocumentFragment().childNodes
throw err
}
}
}
// Common Next.js runtime mocks used across components.
const defaultTestRouter = {
push: vi.fn(),
replace: vi.fn(),
prefetch: vi.fn(),
back: vi.fn(),
forward: vi.fn(),
refresh: vi.fn(),
query: {} as Record<string, any>,
pathname: '/',
asPath: '/',
isReady: true,
events: {
on: vi.fn(),
off: vi.fn(),
emit: vi.fn(),
},
}
vi.mock('next/router', () => ({
useRouter: () => {
const overrides = globalThis.__TEST_ROUTER__ ?? {}
return {
...defaultTestRouter,
...overrides,
query: { ...defaultTestRouter.query, ...(overrides.query ?? {}) },
}
},
default: defaultTestRouter,
}))
vi.mock('next/navigation', () => ({
useRouter: () => ({
push: (globalThis.__TEST_ROUTER__?.push as any) ?? vi.fn(),
replace: (globalThis.__TEST_ROUTER__?.replace as any) ?? vi.fn(),
prefetch: (globalThis.__TEST_ROUTER__?.prefetch as any) ?? vi.fn(),
}),
usePathname: () => globalThis.__TEST_PATHNAME__ ?? '/',
useSearchParams: () =>
globalThis.__TEST_SEARCH_PARAMS__ ?? new URLSearchParams(),
}))
vi.mock('next/image', () => ({
default: (props: any) =>
React.createElement('img', {
...props,
src: typeof props?.src === 'string' ? props.src : props?.src?.src,
}),
}))
vi.mock('next/link', () => ({
default: (props: any) =>
React.createElement(
'a',
{ href: props.href, className: props.className, onClick: props.onClick },
props.children,
),
}))
vi.mock('next/font/google', () => {
const makeFont = () => ({
className: 'font-mock',
variable: '--font-mock',
style: {},
})
return {
Montserrat: makeFont,
Courier_Prime: makeFont,
}
})
vi.mock('next-i18next', () => ({
useTranslation: () => ({
t: (key: string) => key,
i18n: { language: 'en', changeLanguage: vi.fn() },
}),
Trans: ({ i18nKey }: { i18nKey: string }) => i18nKey,
}))
vi.mock('react-oidc-context', () => ({
useAuth: () => ({
isLoading: false,
isAuthenticated: false,
user: null,
error: null,
signinRedirect: vi.fn(),
signoutRedirect: vi.fn(),
...(globalThis.__TEST_AUTH__ ?? {}),
}),
}))
vi.mock('posthog-js', () => ({
default: {
get_distinct_id: () => 'test-posthog-id',
capture: vi.fn(),
},
}))
vi.mock('posthog-js/react', () => ({
usePostHog: () => ({
identify: vi.fn(),
capture: vi.fn(),
}),
}))
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string) => key,
i18n: { language: 'en', changeLanguage: vi.fn() },
}),
}))
beforeAll(() => server.listen())
afterEach(() => {
cleanup()
server.resetHandlers()
globalThis.__TEST_ROUTER__ = undefined
globalThis.__TEST_AUTH__ = undefined
globalThis.__TEST_PATHNAME__ = undefined
globalThis.__TEST_SEARCH_PARAMS__ = undefined
})
afterAll(() => server.close())