-
Notifications
You must be signed in to change notification settings - Fork 452
Expand file tree
/
Copy pathvitest.setup.mts
More file actions
300 lines (266 loc) · 9.12 KB
/
vitest.setup.mts
File metadata and controls
300 lines (266 loc) · 9.12 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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
import '@testing-library/jest-dom/vitest';
import * as crypto from 'node:crypto';
import { TextDecoder, TextEncoder } from 'node:util';
import { cleanup, configure } from '@testing-library/react';
import { afterAll, afterEach, beforeAll, beforeEach, vi } from 'vitest';
configure({ asyncUtilTimeout: 5000 });
// Track all timers created during tests to clean them up
const activeTimers = new Set<ReturnType<typeof setTimeout>>();
const originalSetTimeout = global.setTimeout;
const originalClearTimeout = global.clearTimeout;
// Wrap setTimeout to track all timers
global.setTimeout = ((callback: any, delay?: any, ...args: any[]) => {
const timerId = originalSetTimeout(callback, delay, ...args);
activeTimers.add(timerId);
return timerId;
}) as typeof setTimeout;
// Wrap clearTimeout to remove from tracking
global.clearTimeout = ((timerId?: ReturnType<typeof setTimeout>) => {
if (timerId) {
activeTimers.delete(timerId);
originalClearTimeout(timerId);
}
}) as typeof clearTimeout;
beforeEach(() => {
activeTimers.clear();
});
afterEach(() => {
cleanup();
// Clear all tracked timers to prevent post-test execution
activeTimers.forEach(timerId => originalClearTimeout(timerId));
activeTimers.clear();
});
// Store the original method
// eslint-disable-next-line @typescript-eslint/unbound-method
const ogToLocaleDateString = Date.prototype.toLocaleDateString;
beforeAll(() => {
// Make sure our tests always use the same locale
Date.prototype.toLocaleDateString = function (...args: any[]) {
// Call original method with 'en-US' locale
return ogToLocaleDateString.call(this, 'en-US', args[1]); // Pass options if provided
};
// Keep locale and timezone deterministic across test environments.
// Set a default timezone (e.g., UTC) for consistency
process.env.TZ = 'UTC';
});
afterAll(() => {
// Restore original Date method
Date.prototype.toLocaleDateString = ogToLocaleDateString;
});
// Shared DOM and runtime setup for component tests.
// Mock Response class if not already defined by jsdom/happy-dom
class FakeResponse {}
// Polyfill/mock global objects for the jsdom environment
if (typeof window !== 'undefined') {
Object.defineProperties(globalThis, {
TextDecoder: { value: TextDecoder },
TextEncoder: { value: TextEncoder },
Response: { value: FakeResponse },
crypto: { value: crypto.webcrypto },
isSecureContext: { value: true, writable: true },
});
// Mock ResizeObserver
window.ResizeObserver =
window.ResizeObserver ||
(vi.fn().mockImplementation(function () {
return {
disconnect: vi.fn(),
observe: vi.fn(),
unobserve: vi.fn(),
};
}) as unknown as typeof ResizeObserver);
// Mock matchMedia
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: vi.fn().mockImplementation(query => ({
matches: false,
media: query,
onchange: null,
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
})),
});
// Mock document.elementFromPoint for input-otp library
Object.defineProperty(document, 'elementFromPoint', {
value: vi.fn().mockReturnValue(null),
writable: true,
});
Object.defineProperty(window.navigator, 'language', {
writable: true,
configurable: true,
value: '',
});
// Mock IntersectionObserver
//@ts-expect-error - Mocking class
globalThis.IntersectionObserver = class IntersectionObserver {
constructor() {}
disconnect() {
return null;
}
observe() {
return null;
}
takeRecords() {
return []; // Return empty array as per spec
}
unobserve() {
return null;
}
};
// Mock HTMLCanvasElement.prototype.getContext to prevent errors
HTMLCanvasElement.prototype.getContext = vi.fn().mockImplementation((contextType: string) => {
if (contextType === '2d') {
return {
fillRect: vi.fn(),
getImageData: vi.fn(() => ({ data: new Uint8ClampedArray([255, 255, 255, 255]) }) as unknown as ImageData),
} as unknown as CanvasRenderingContext2D;
}
if (contextType === 'webgl' || contextType === 'webgl2') {
return {} as unknown as WebGLRenderingContext;
}
return null;
});
// Mock Element.prototype.animate for auto-animate library
Element.prototype.animate = vi.fn().mockImplementation(() => ({
cancel: vi.fn(),
finish: vi.fn(),
pause: vi.fn(),
play: vi.fn(),
reverse: vi.fn(),
updatePlaybackRate: vi.fn(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
}));
// Mock requestAnimationFrame for auto-animate library
let animationFrameHandleCounter = 0;
const animationFrameTimeouts = new Map<number, NodeJS.Timeout>();
let isTestEnvironmentActive = true;
const mockRequestAnimationFrame = vi.fn().mockImplementation((callback: FrameRequestCallback) => {
const handle = ++animationFrameHandleCounter;
const timeoutId = global.setTimeout(() => {
// Only execute callback if test environment is still active
if (isTestEnvironmentActive) {
callback(performance.now());
}
animationFrameTimeouts.delete(handle);
}, 0);
animationFrameTimeouts.set(handle, timeoutId);
return handle;
});
const mockCancelAnimationFrame = vi.fn().mockImplementation((handle: number) => {
const timeoutId = animationFrameTimeouts.get(handle);
if (timeoutId) {
global.clearTimeout(timeoutId);
animationFrameTimeouts.delete(handle);
}
});
// Cleanup function to prevent post-test execution
const cleanupAnimationFrames = () => {
isTestEnvironmentActive = false;
// Clear all pending animation frames
for (const timeoutId of animationFrameTimeouts.values()) {
global.clearTimeout(timeoutId);
}
animationFrameTimeouts.clear();
};
// Register cleanup to run after each test
afterEach(() => {
cleanupAnimationFrames();
// Reset for next test
isTestEnvironmentActive = true;
});
global.requestAnimationFrame = mockRequestAnimationFrame;
global.cancelAnimationFrame = mockCancelAnimationFrame;
window.requestAnimationFrame = mockRequestAnimationFrame;
window.cancelAnimationFrame = mockCancelAnimationFrame;
// Patch JSDOM's getComputedStyle to handle null/undefined elements gracefully
// This prevents the "Cannot convert undefined or null to object" error
const originalGetComputedStyle = window.getComputedStyle.bind(window);
const patchedGetComputedStyle: typeof window.getComputedStyle = (element, pseudoElement) => {
const el = element as unknown as Element | null;
if (!element) {
// Return a minimal CSSStyleDeclaration object for null elements
return {
getPropertyValue: () => '',
setProperty: () => {},
removeProperty: () => '',
item: () => '',
length: 0,
parentRule: null,
cssText: '',
display: 'none',
visibility: 'hidden',
opacity: '0',
position: 'static',
overflow: 'visible',
clip: 'auto',
clipPath: 'none',
transform: 'none',
filter: 'none',
backfaceVisibility: 'visible',
perspective: 'none',
willChange: 'auto',
} as unknown as CSSStyleDeclaration;
}
try {
return originalGetComputedStyle(el as Element, (pseudoElement ?? null) as any);
} catch {
// If JSDOM fails, return a safe fallback
return {
getPropertyValue: () => '',
setProperty: () => {},
removeProperty: () => '',
item: () => '',
length: 0,
parentRule: null,
cssText: '',
display: 'block',
visibility: 'visible',
opacity: '1',
position: 'static',
overflow: 'visible',
clip: 'auto',
clipPath: 'none',
transform: 'none',
filter: 'none',
backfaceVisibility: 'visible',
perspective: 'none',
willChange: 'auto',
} as unknown as CSSStyleDeclaration;
}
};
window.getComputedStyle = patchedGetComputedStyle;
}
// Mock @formkit/auto-animate to prevent timers leaking after test teardown.
// The __mocks__ directory in src/elements/ is not detected by Vitest for
// node_module mocks, so we need an explicit vi.mock here.
vi.mock('@formkit/auto-animate/react', () => ({
useAutoAnimate: () => [null],
}));
// Also mock the base module to prevent its side effects (setInterval/setTimeout
// that call requestAnimationFrame) from firing after jsdom environment teardown.
vi.mock('@formkit/auto-animate', () => ({
default: () => ({ enable: () => {}, disable: () => {}, destroy: () => {} }),
}));
// Mock browser-tabs-lock to prevent window access errors in tests
vi.mock('browser-tabs-lock', () => {
return {
default: vi.fn().mockImplementation(function () {
return {
acquireLock: vi.fn().mockResolvedValue(true),
releaseLock: vi.fn().mockResolvedValue(true),
};
}),
};
});
// Mock browser extension APIs when a test needs them.
// Example: Mocking chrome.runtime.sendMessage
// global.chrome = {
// runtime: {
// sendMessage: vi.fn(),
// // ... other chrome APIs needed
// },
// // ... other chrome namespaces needed
// };