-
-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathvitest-setup.tsx
More file actions
504 lines (459 loc) · 12.3 KB
/
Copy pathvitest-setup.tsx
File metadata and controls
504 lines (459 loc) · 12.3 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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
// Some portions generated by Co-Pilot
import React from "react";
import { vi, expect, afterEach, afterAll } from "vitest";
import * as matchers from "vitest-axe/matchers";
import * as Highcharts from "highcharts";
import * as jestDomMatchers from "@testing-library/jest-dom/matchers";
import { configMocks, mockAnimationsApi } from "jsdom-testing-mocks";
configMocks({ afterEach, afterAll });
mockAnimationsApi();
Highcharts.useSerialIds(true);
Highcharts.AST.allowedAttributes.push("rel");
// jsdom does not implement getComputedStyle() for pseudo-elements and logs a
// console error for every call. Suppress it to keep test output clean.
const originalGetComputedStyle = window.getComputedStyle;
window.getComputedStyle = (elt: Element, pseudoElt?: string | null) => {
if (pseudoElt) return {} as CSSStyleDeclaration;
return originalGetComputedStyle(elt);
};
// This explicitly adds the accessibility matchers to Vitest
expect.extend(matchers);
// This extends Vitest's expect with Jest-DOM matchers
expect.extend(jestDomMatchers);
// Mock GSAP and ScrollTrigger
vi.mock("gsap", () => {
const mockGsap = {
registerPlugin: vi.fn(),
to: vi.fn(),
from: vi.fn(),
fromTo: vi.fn(),
set: vi.fn(),
timeline: vi.fn(() => ({
to: vi.fn(),
from: vi.fn(),
fromTo: vi.fn(),
add: vi.fn(),
})),
};
return {
gsap: mockGsap,
default: mockGsap,
};
});
// Create a mock for ScrollTrigger before other imports can use it
const mockScrollTrigger = {
create: vi.fn(() => ({
kill: vi.fn(),
progress: 0,
})),
refresh: vi.fn(),
update: vi.fn(),
getAll: vi.fn(() => []),
killAll: vi.fn(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
};
vi.mock("gsap/ScrollTrigger", () => {
return {
ScrollTrigger: mockScrollTrigger,
};
});
// Mock the useTranslations hook to return a simple text value with rich formatting support
vi.mock("next-intl", () => ({
useTranslations: () => {
// Create a translator function with rich text support
const translator = (key: string) => "Text";
// Add rich method to support rich text formatting with components
translator.rich = (key: string, options?: Record<string, any>) => {
if (options) {
return "Text";
}
return "Text";
};
return translator;
},
useLocale: () => "en",
// Add other exports that might be used in your app
NextIntlClientProvider: ({ children }: { children: React.ReactNode }) => (
<>{children}</>
),
}));
// Mock motion/react
vi.mock("motion/react", () => {
const filterMotionProps = (props: any) => {
const {
initial,
animate,
exit,
whileInView,
whileHover,
whileTap,
whileDrag,
whileFocus,
viewport,
transition,
variants,
onAnimationStart,
onAnimationComplete,
onUpdate,
drag,
dragControls,
dragListener,
dragConstraints,
dragElastic,
dragMomentum,
dragPropagation,
dragSnapToOrigin,
layout,
layoutId,
layoutDependency,
layoutScroll,
...validProps
} = props;
return validProps;
};
return {
motion: {
div: ({ children, ...props }: any) => (
<div {...filterMotionProps(props)}>{children}</div>
),
h3: ({ children, ...props }: any) => (
<h3 {...filterMotionProps(props)}>{children}</h3>
),
p: ({ children, ...props }: any) => (
<p {...filterMotionProps(props)}>{children}</p>
),
span: ({ children, ...props }: any) => (
<span {...filterMotionProps(props)}>{children}</span>
),
section: ({ children, ...props }: any) => (
<section {...filterMotionProps(props)}>{children}</section>
),
article: ({ children, ...props }: any) => (
<article {...filterMotionProps(props)}>{children}</article>
),
ul: ({ children, ...props }: any) => (
<ul {...filterMotionProps(props)}>{children}</ul>
),
li: ({ children, ...props }: any) => (
<li {...filterMotionProps(props)}>{children}</li>
),
a: ({ children, ...props }: any) => (
<a {...filterMotionProps(props)}>{children}</a>
),
button: ({ children, ...props }: any) => (
<button {...filterMotionProps(props)}>{children}</button>
),
img: ({ children, ...props }: any) => (
<img {...filterMotionProps(props)} />
),
},
useScroll: () => ({ scrollYProgress: { get: () => 0 } }),
useTransform: () => 0,
AnimatePresence: ({ children }: any) => <>{children}</>,
};
});
// Mock next/image
vi.mock("next/image", () => ({
default: ({
src,
alt,
fill,
priority,
quality,
placeholder,
blurDataURL,
loader,
unoptimized,
...props
}: any) => <img src={src} alt={alt} {...props} />,
}));
vi.mock("@/i18n/navigation", () => ({
redirect: vi.fn(),
usePathname: vi.fn(() => "/en"),
useRouter: vi.fn(() => ({ push: vi.fn(), replace: vi.fn() })),
getPathname: vi.fn(() => "/docs"),
Link: ({
href,
children,
...props
}: {
href: string;
children: React.ReactNode;
[key: string]: any;
}) => (
<a href={href} {...props}>
{children}
</a>
),
}));
// Mock the useAdoptiumContributorsApi hook
vi.mock("@/hooks/useAdoptiumContributorsApi", () => ({
useAdoptiumContributorsApi: () => null,
}));
// Mock adopters data so adding new logos doesn't break snapshots
vi.mock("@/data/adopters.json", () => ({
default: [
{
name: "Mock Adopter",
logo: "adopters/mock-adopter.svg",
url: "https://mock-adopter.example.com",
tier: "adopters",
featured: true,
logo_white: "adopters/mock-adopter-white.svg",
logoPadding: "1em",
},
],
}));
// Mock shuffle to return input unchanged for deterministic snapshots
vi.mock("@/utils/shuffle", () => ({
shuffle: <T,>(arr: T[]) => arr,
}));
type SwiperProps = {
children: React.ReactNode;
};
vi.mock("swiper/react", () => ({
Swiper: React.forwardRef<HTMLDivElement, SwiperProps>(({ children }, ref) => {
// Create a mock swiper object with an init method
const mockSwiper = {
init: () => vi.fn(),
update: () => vi.fn(),
slideNext: () => vi.fn(),
slidePrev: () => vi.fn(),
};
// Use a callback ref to assign the mock swiper object to the ref
React.useEffect(() => {
if (ref && typeof ref !== "function") {
(ref as React.RefObject<any>).current = { swiper: mockSwiper };
}
}, [ref]);
return <div data-testid="Swiper">{children}</div>;
}),
SwiperSlide: ({ children }: { children: React.ReactNode }) => (
<div data-testid="SwiperSlide">{children}</div>
),
}));
class IntersectionObserverMock {
root: Element | Document | null = null;
rootMargin: string = "0px";
thresholds: ReadonlyArray<number> = [0];
callback: IntersectionObserverCallback;
constructor(callback: IntersectionObserverCallback) {
this.callback = callback;
}
observe() {
// When observe is called, trigger the callback with a mock entry
if (typeof this.callback === "function") {
// Create a DOMRect
const rect = {
bottom: 0,
height: 0,
left: 0,
right: 0,
top: 0,
width: 0,
x: 0,
y: 0,
toJSON: () => {},
} as DOMRectReadOnly;
const mockEntry = {
isIntersecting: true,
boundingClientRect: rect,
intersectionRatio: 1,
intersectionRect: rect,
rootBounds: null,
target: document.createElement("div"),
time: Date.now(),
} as IntersectionObserverEntry;
this.callback([mockEntry], this as unknown as IntersectionObserver);
}
}
unobserve() {}
disconnect() {}
takeRecords() {
return [];
}
}
vi.stubGlobal("IntersectionObserver", IntersectionObserverMock as any);
class ResizeObserverMock {
callback: ResizeObserverCallback;
constructor(callback: ResizeObserverCallback) {
this.callback = callback;
}
observe() {
// Trigger callback with mock entries
const mockEntry = {
target: document.createElement("div"),
contentRect: {
width: 0,
height: 0,
top: 0,
left: 0,
bottom: 0,
right: 0,
x: 0,
y: 0,
toJSON: () => {},
},
borderBoxSize: [{ inlineSize: 0, blockSize: 0 }],
contentBoxSize: [{ inlineSize: 0, blockSize: 0 }],
devicePixelContentBoxSize: [{ inlineSize: 0, blockSize: 0 }],
} as ResizeObserverEntry;
if (typeof this.callback === "function") {
this.callback([mockEntry], this as unknown as ResizeObserver);
}
}
unobserve() {}
disconnect() {}
}
vi.stubGlobal("ResizeObserver", ResizeObserverMock as any);
// Mock fetch API to handle network requests
global.fetch = vi.fn().mockImplementation((url) => {
// Mock response for download stats API
if (
url === "https://api.adoptium.net/v3/stats/downloads/total" ||
url.toString().includes("api.adoptium.net/v3/stats/downloads/total")
) {
return Promise.resolve({
ok: true,
json: () =>
Promise.resolve({
total_downloads: {
total: 1234567890,
},
}),
});
}
// Default mock response
return Promise.resolve({
ok: true,
json: () => Promise.resolve({}),
});
});
/**
* fix: `matchMedia` not present, legacy browsers require a polyfill
*/
global.matchMedia =
global.matchMedia ||
function (query) {
return {
matches: false,
media: query,
onchange: null,
// Legacy API
addListener: function () {},
removeListener: function () {},
// Modern API
addEventListener: function () {},
removeEventListener: function () {},
dispatchEvent: function () {
return false;
},
};
};
/**
* Mock localStorage
*/
const localStorageMock = (() => {
let store: Record<string, string> = {};
return {
getItem: (key: string) => {
return store[key] || null;
},
setItem: (key: string, value: string) => {
store[key] = value.toString();
},
removeItem: (key: string) => {
delete store[key];
},
clear: () => {
store = {};
},
};
})();
Object.defineProperty(window, "localStorage", {
value: localStorageMock,
});
/**
* Mock canvas getContext for accessibility tests
* This prevents the "Not implemented: HTMLCanvasElement.prototype.getContext" error
*/
if (typeof HTMLCanvasElement !== "undefined") {
// @ts-expect-error - We are mocking getContext
HTMLCanvasElement.prototype.getContext = vi.fn(() => ({
fillRect: vi.fn(),
clearRect: vi.fn(),
getImageData: vi.fn(() => ({
data: new Array(4),
})),
putImageData: vi.fn(),
createImageData: vi.fn(() => []),
setTransform: vi.fn(),
drawImage: vi.fn(),
save: vi.fn(),
fillText: vi.fn(),
restore: vi.fn(),
beginPath: vi.fn(),
moveTo: vi.fn(),
lineTo: vi.fn(),
closePath: vi.fn(),
stroke: vi.fn(),
translate: vi.fn(),
scale: vi.fn(),
rotate: vi.fn(),
arc: vi.fn(),
fill: vi.fn(),
measureText: vi.fn(() => ({ width: 0 })),
transform: vi.fn(),
rect: vi.fn(),
clip: vi.fn(),
}));
}
/**
* Mock for react-slick to avoid "window is not defined" errors in tests
*/
vi.mock("react-slick", () => {
const Slider = ({
children,
className,
}: {
children: React.ReactNode;
className?: string;
}) => {
return (
<div data-testid="react-slick-mock" className={className || ""}>
{children}
</div>
);
};
Slider.defaultProps = {
dots: false,
infinite: true,
speed: 500,
slidesToShow: 1,
slidesToScroll: 1,
};
return {
__esModule: true,
default: Slider,
};
});
// Mock slick-carousel CSS imports that might be required by components
vi.mock("slick-carousel/slick/slick.css", () => ({}));
vi.mock("slick-carousel/slick/slick-theme.css", () => ({}));
/**
* Suppress jsdom "Not implemented" warnings for getComputedStyle with pseudo-elements.
* jsdom does not support pseudo-element selectors; these warnings are harmless noise.
*/
const originalConsoleError = console.error;
console.error = (...args: any[]) => {
if (
typeof args[0] === "string" &&
args[0].includes("Not implemented: Window's getComputedStyle()")
) {
return;
}
originalConsoleError(...args);
};
// Export everything from testing-library/react
export * from "@testing-library/react";