-
-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathjest.setup.ts
More file actions
77 lines (75 loc) · 2.71 KB
/
jest.setup.ts
File metadata and controls
77 lines (75 loc) · 2.71 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
import '@testing-library/jest-dom';
// Polyfill global Request for Next's Request/Response helpers when running in Node
if (typeof (global as any).Request === 'undefined') {
// Minimal, lightweight Request polyfill sufficient for tests that only need
// to construct Request-like objects. This avoids adding native deps like
// undici and keeps tests fast and hermetic.
(global as any).Request = class Request {
url: string;
method: string;
headers: { get: (name: string) => string | null };
private _body: any;
constructor(input: any, init: any = {}) {
this.url = typeof input === 'string' ? input : input?.url || '';
this.method = init.method || 'GET';
const rawHeaders = init.headers || {};
// simple Headers-like object with `get` to satisfy Next's helpers
this.headers = {
get: (name: string) => {
const key = Object.keys(rawHeaders).find(k => k.toLowerCase() === name.toLowerCase());
if (!key) return null;
return rawHeaders[key];
},
};
this._body = init?.body;
}
async json() {
if (typeof this._body === 'string') return JSON.parse(this._body);
return this._body;
}
async text() {
if (typeof this._body === 'string') return this._body;
return JSON.stringify(this._body);
}
clone() {
return new (global as any).Request(this.url, { method: this.method, headers: this.headers, body: this._body });
}
};
// Minimal Response polyfill
(global as any).Response = class Response {
status: number;
headers: { get: (name: string) => string | null };
body: any;
constructor(body: any = null, init: any = {}) {
this.body = body;
this.status = init.status || 200;
const rawHeaders = init.headers || {};
if (rawHeaders && typeof rawHeaders.get === 'function') {
// Already a Headers-like object
this.headers = rawHeaders;
} else {
this.headers = {
get: (name: string) => {
const key = Object.keys(rawHeaders).find(k => k.toLowerCase() === name.toLowerCase());
if (!key) return null;
return rawHeaders[key];
},
};
}
}
static json(body: any, init: any = {}) {
return new (global as any).Response(body, { status: init.status || 200, headers: init.headers || {} });
}
async json() {
if (typeof this.body === 'string') return JSON.parse(this.body);
return this.body;
}
async text() {
if (typeof this.body === 'string') return this.body;
return JSON.stringify(this.body);
}
clone() {
return new (global as any).Response(this.body, { status: this.status, headers: this.headers });
}
};
}