-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjest.setup.js
More file actions
458 lines (412 loc) · 11.9 KB
/
jest.setup.js
File metadata and controls
458 lines (412 loc) · 11.9 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
import '@testing-library/jest-dom';
// Polyfills for Next.js 15 web APIs
import { TextDecoder, TextEncoder } from 'util';
import { ReadableStream, WritableStream, TransformStream } from 'stream/web';
// Add polyfills to global scope
Object.assign(global, {
TextDecoder,
TextEncoder,
ReadableStream,
WritableStream,
TransformStream,
});
// Mock Web APIs for Next.js 15
const mockHeaders = class Headers {
constructor(init) {
this._headers = new Map();
if (init) {
if (Array.isArray(init)) {
init.forEach(([key, value]) => this._headers.set(key.toLowerCase(), value));
} else if (init instanceof Headers) {
init.forEach((value, key) => this._headers.set(key, value));
} else {
Object.entries(init).forEach(([key, value]) => {
this._headers.set(key.toLowerCase(), value);
});
}
}
}
append(name, value) {
this._headers.set(name.toLowerCase(), value);
}
delete(name) {
this._headers.delete(name.toLowerCase());
}
get(name) {
return this._headers.get(name.toLowerCase()) || null;
}
has(name) {
return this._headers.has(name.toLowerCase());
}
set(name, value) {
this._headers.set(name.toLowerCase(), value);
}
forEach(callback, thisArg) {
this._headers.forEach((value, key) => {
callback.call(thisArg, value, key, this);
});
}
keys() {
return this._headers.keys();
}
values() {
return this._headers.values();
}
entries() {
return this._headers.entries();
}
[Symbol.iterator]() {
return this._headers.entries();
}
};
const mockRequest = class Request {
constructor(input, init = {}) {
this.url = typeof input === 'string' ? input : input.url;
this.method = init.method || 'GET';
this.headers = new mockHeaders(init.headers);
this.body = init.body || null;
this.bodyUsed = false;
this.cache = init.cache || 'default';
this.credentials = init.credentials || 'same-origin';
this.destination = init.destination || '';
this.integrity = init.integrity || '';
this.keepalive = init.keepalive || false;
this.mode = init.mode || 'cors';
this.redirect = init.redirect || 'follow';
this.referrer = init.referrer || 'about:client';
this.referrerPolicy = init.referrerPolicy || '';
this.signal = init.signal || null;
}
async arrayBuffer() {
this.bodyUsed = true;
return new ArrayBuffer(0);
}
async blob() {
this.bodyUsed = true;
return new Blob([]);
}
async formData() {
this.bodyUsed = true;
return new FormData();
}
async json() {
this.bodyUsed = true;
return this.body ? JSON.parse(this.body) : {};
}
async text() {
this.bodyUsed = true;
return this.body || '';
}
clone() {
return new Request(this.url, this);
}
};
const mockResponse = class Response {
constructor(body, init = {}) {
this.body = body;
this.bodyUsed = false;
this.headers = new mockHeaders(init.headers);
this.ok = (init.status || 200) >= 200 && (init.status || 200) < 300;
this.redirected = init.redirected || false;
this.status = init.status || 200;
this.statusText = init.statusText || 'OK';
this.type = init.type || 'default';
this.url = init.url || '';
}
async arrayBuffer() {
this.bodyUsed = true;
return new ArrayBuffer(0);
}
async blob() {
this.bodyUsed = true;
return new Blob([this.body]);
}
async formData() {
this.bodyUsed = true;
return new FormData();
}
async json() {
this.bodyUsed = true;
return typeof this.body === 'string' ? JSON.parse(this.body) : this.body;
}
async text() {
this.bodyUsed = true;
return typeof this.body === 'string' ? this.body : JSON.stringify(this.body);
}
clone() {
return new Response(this.body, this);
}
static json(data, init) {
return new Response(JSON.stringify(data), {
...init,
headers: {
'content-type': 'application/json',
...init?.headers,
},
});
}
static error() {
return new Response(null, { status: 0, statusText: '' });
}
static redirect(url, status = 302) {
return new Response(null, { status, headers: { location: url } });
}
};
// Add to global scope
Object.assign(global, {
Headers: mockHeaders,
Request: mockRequest,
Response: mockResponse,
fetch: jest.fn(),
});
// Mock Next.js server APIs
const mockNextRequest = class NextRequest extends mockRequest {
constructor(input, init = {}) {
super(input, init);
this.nextUrl = new URL(this.url);
this.ip = '127.0.0.1';
this.geo = {};
this.cookies = new Map();
}
};
const mockNextResponse = class NextResponse extends mockResponse {
static json(data, init) {
return new mockNextResponse(JSON.stringify(data), {
...init,
headers: {
'content-type': 'application/json',
...init?.headers,
},
});
}
static redirect(url, status = 302) {
return new mockNextResponse(null, { status, headers: { location: url } });
}
static rewrite(destination) {
return new mockNextResponse(null, { headers: { 'x-middleware-rewrite': destination } });
}
static next() {
return new mockNextResponse(null, { headers: { 'x-middleware-next': '1' } });
}
};
// Mock Next.js server module
jest.doMock('next/server', () => ({
NextRequest: mockNextRequest,
NextResponse: mockNextResponse,
}));
// Mock Supabase environment variables and client
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://test.supabase.co';
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY = 'test-anon-key';
process.env.SUPABASE_SERVICE_ROLE_KEY = 'test-service-role-key';
// Create a shared mock client that can be imported by tests
const createMockSupabaseClient = () => ({
auth: {
signInWithPassword: jest.fn().mockResolvedValue({
data: { user: null, session: null },
error: null
}),
signUp: jest.fn().mockResolvedValue({
data: { user: null },
error: null
}),
signOut: jest.fn().mockResolvedValue({
error: null
}),
getSession: jest.fn().mockResolvedValue({
data: { session: null },
error: null
}),
getUser: jest.fn().mockResolvedValue({
data: { user: null },
error: null
}),
refreshSession: jest.fn().mockResolvedValue({
data: { session: null },
error: null
}),
onAuthStateChange: jest.fn(() => ({
data: { subscription: { unsubscribe: jest.fn() } }
})),
},
from: jest.fn(() => ({
select: jest.fn().mockReturnThis(),
insert: jest.fn().mockReturnThis(),
update: jest.fn().mockReturnThis(),
delete: jest.fn().mockReturnThis(),
eq: jest.fn().mockReturnThis(),
neq: jest.fn().mockReturnThis(),
gt: jest.fn().mockReturnThis(),
gte: jest.fn().mockReturnThis(),
lt: jest.fn().mockReturnThis(),
lte: jest.fn().mockReturnThis(),
like: jest.fn().mockReturnThis(),
ilike: jest.fn().mockReturnThis(),
is: jest.fn().mockReturnThis(),
in: jest.fn().mockReturnThis(),
contains: jest.fn().mockReturnThis(),
containedBy: jest.fn().mockReturnThis(),
rangeGt: jest.fn().mockReturnThis(),
rangeGte: jest.fn().mockReturnThis(),
rangeLt: jest.fn().mockReturnThis(),
rangeLte: jest.fn().mockReturnThis(),
rangeAdjacent: jest.fn().mockReturnThis(),
overlaps: jest.fn().mockReturnThis(),
textSearch: jest.fn().mockReturnThis(),
not: jest.fn().mockReturnThis(),
or: jest.fn().mockReturnThis(),
order: jest.fn().mockReturnThis(),
limit: jest.fn().mockReturnThis(),
range: jest.fn().mockReturnThis(),
single: jest.fn().mockResolvedValue({ data: null, error: null }),
maybeSingle: jest.fn().mockResolvedValue({ data: null, error: null }),
})),
});
// Global Supabase client mock instance
global.mockSupabaseClient = createMockSupabaseClient();
// Mock Supabase client creation functions
jest.mock('@/lib/supabase/server', () => {
const mockClient = {
from: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
eq: jest.fn().mockReturnValue({
single: jest.fn().mockResolvedValue({ data: null, error: null })
})
}),
insert: jest.fn().mockResolvedValue({ data: null, error: null }),
update: jest.fn().mockReturnValue({
eq: jest.fn().mockResolvedValue({ data: null, error: null })
}),
delete: jest.fn().mockReturnValue({
eq: jest.fn().mockResolvedValue({ data: null, error: null })
})
}),
auth: {
getUser: jest.fn().mockResolvedValue({ data: { user: null }, error: null }),
signUp: jest.fn().mockResolvedValue({ data: { user: null }, error: null }),
signInWithPassword: jest.fn().mockResolvedValue({ data: { user: null }, error: null }),
signOut: jest.fn().mockResolvedValue({ error: null })
},
rpc: jest.fn().mockResolvedValue({ data: null, error: null })
};
return {
createClient: jest.fn(() => {
// Support both sync and async patterns
const client = mockClient;
client.then = (onResolve) => Promise.resolve(mockClient).then(onResolve);
return client;
}),
createClientSync: jest.fn(() => mockClient),
createServiceRoleClient: jest.fn(() => mockClient),
};
});
// Mock rate limiter for API tests
jest.mock('@/lib/rate-limiter', () => ({
checkRateLimit: jest.fn().mockResolvedValue({
allowed: true,
response: null
}),
resetRateLimit: jest.fn().mockResolvedValue(),
}));
// Mock auth validation
jest.mock('@/lib/validation/auth', () => ({
loginSchema: {
safeParse: jest.fn().mockReturnValue({
success: true,
data: {}
})
},
signupSchema: {
safeParse: jest.fn().mockReturnValue({
success: true,
data: {}
})
},
validate: jest.fn((schema, data) => ({ ok: true, data })),
}));
// Mock client-side supabase
jest.mock('@/lib/supabase/client', () => {
return {
createClient: jest.fn(() => global.mockSupabaseClient),
};
});
// Mock Next.js router
jest.mock('next/navigation', () => ({
useRouter: jest.fn(() => ({
push: jest.fn(),
replace: jest.fn(),
back: jest.fn(),
forward: jest.fn(),
refresh: jest.fn(),
prefetch: jest.fn()
})),
useSearchParams: jest.fn(() => ({
get: jest.fn()
})),
usePathname: jest.fn(() => '/')
}));
// Mock Next.js Link component
jest.mock('next/link', () => {
return ({ children, href, ...props }) => {
return <a href={href} {...props}>{children}</a>;
};
});
// Global test utilities
global.ResizeObserver = jest.fn().mockImplementation(() => ({
observe: jest.fn(),
unobserve: jest.fn(),
disconnect: jest.fn(),
}));
// Mock IntersectionObserver
global.IntersectionObserver = jest.fn().mockImplementation(() => ({
observe: jest.fn(),
unobserve: jest.fn(),
disconnect: jest.fn(),
}));
// Mock scrollIntoView (only in browser environment)
if (typeof Element !== 'undefined') {
Element.prototype.scrollIntoView = jest.fn();
}
// Mock matchMedia (only in browser environment)
if (typeof window !== 'undefined') {
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation(query => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(),
removeListener: jest.fn(),
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});
}
// Suppress console.error and console.warn in tests unless they are expected
const originalError = console.error;
const originalWarn = console.warn;
beforeAll(() => {
console.error = (...args) => {
if (
typeof args[0] === 'string' &&
args[0].includes('Warning: ReactDOM.render is deprecated')
) {
return;
}
originalError.call(console, ...args);
};
console.warn = (...args) => {
if (
typeof args[0] === 'string' &&
(args[0].includes('componentWillReceiveProps') ||
args[0].includes('componentWillUpdate'))
) {
return;
}
originalWarn.call(console, ...args);
};
});
afterAll(() => {
console.error = originalError;
console.warn = originalWarn;
});