-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjest.setup.js
88 lines (73 loc) · 1.93 KB
/
jest.setup.js
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
// Learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom'
// Mock NextResponse
const NextResponse = {
json: (body, init = {}) => {
const response = new Response(JSON.stringify(body), {
...init,
headers: {
'Content-Type': 'application/json',
...(init.headers || {})
}
})
// Add status and ok properties
Object.defineProperty(response, 'status', {
get() { return init.status || 200 }
})
Object.defineProperty(response, 'ok', {
get() { return response.status >= 200 && response.status < 300 }
})
// Add json method
response.json = async () => body
return response
}
}
global.NextResponse = NextResponse
// Mock FormData
class FormData {
constructor() {
this.data = new Map()
}
append(key, value) {
this.data.set(key, value)
}
get(key) {
return this.data.get(key)
}
entries() {
return Array.from(this.data.entries())
}
}
global.FormData = FormData
// Mock fetch globally
global.fetch = jest.fn()
// Setup Request and Response constructors for Next.js API routes
if (typeof Request !== 'function') {
global.Request = class Request {
constructor(input, init) {
this.url = input
this.method = init?.method || 'GET'
this._body = init?.body
this.headers = new Map(Object.entries(init?.headers || {}))
}
async formData() {
if (this._body instanceof FormData) {
return this._body
}
throw new Error('Body is not FormData')
}
}
}
if (typeof Response !== 'function') {
global.Response = class Response {
constructor(body, init = {}) {
this._body = body
this.status = init.status || 200
this.ok = this.status >= 200 && this.status < 300
this.headers = new Map(Object.entries(init.headers || {}))
}
async json() {
return typeof this._body === 'string' ? JSON.parse(this._body) : this._body
}
}
}