-
Notifications
You must be signed in to change notification settings - Fork 69
/
body.test.ts
234 lines (190 loc) · 6.65 KB
/
body.test.ts
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
const testOrSkip =
process.versions.node.split('.').map(Number)[0] > 16 ? test : test.skip
testOrSkip('throws when the body was directly consumed', async () => {
expect.assertions(9)
const object = { hello: 'world' }
const blob = new Blob([JSON.stringify(object, null, 2)], {
type: 'application/json',
})
const formData = new FormData()
formData.append('name', 'John')
formData.append('lastname', 'Doe')
formData.append('metadata', blob)
const response = new Response(formData)
async function* streamToIterator<T>(
readable: ReadableStream<T>,
): AsyncIterableIterator<T> {
const reader = readable.getReader()
while (true) {
const { value, done } = await reader.read()
if (done) break
if (value != null) {
yield value
}
}
reader.releaseLock()
}
// @ts-expect-error
for await (const item of streamToIterator(response.body)) {
expect(item).toBeTruthy()
}
// @ts-expect-error
const reader = response.body.getReader()
const { done } = await reader.read()
expect(done).toBeTruthy()
const error = await response.text().catch((err) => err)
expectErrorInstanceOf(error, TypeError)
expect(error.message).toEqual('Body is unusable')
})
testOrSkip('throws when the body was indirectly consumed', async () => {
expect.assertions(3)
const object = { hello: 'world' }
const blob = new Blob([JSON.stringify(object, null, 2)], {
type: 'application/json',
})
const formData = new FormData()
formData.append('name', 'John')
formData.append('lastname', 'Doe')
formData.append('metadata', blob)
const response = new Response(formData)
const text = await response.text()
expect(text).toBeTruthy()
const error = await response.text().catch((err) => err)
expectErrorInstanceOf(error, TypeError)
expect(error.message).toEqual('Body is unusable')
})
testOrSkip('allows to read a FormData body as text', async () => {
const object = { hello: 'world' }
const blob = new Blob([JSON.stringify(object, null, 2)], {
type: 'application/json',
})
const formData = new FormData()
formData.append('name', 'John')
formData.append('lastname', 'Doe')
formData.append('metadata', blob)
const res = new Response(formData)
const text = await res?.text()
expect(text.replace(/formdata-undici-0\d+/g, 'formdata-unidici-0.1234'))
.toMatchInlineSnapshot(`
"------formdata-unidici-0.1234
Content-Disposition: form-data; name="name"
John
------formdata-unidici-0.1234
Content-Disposition: form-data; name="lastname"
Doe
------formdata-unidici-0.1234
Content-Disposition: form-data; name="metadata"; filename="blob"
Content-Type: application/json
{
"hello": "world"
}
------formdata-unidici-0.1234--"
`)
})
testOrSkip('allows to read a null body as ArrayBuffer', async () => {
const response = new Response(null)
const buffer = await response.arrayBuffer()
expect(buffer.byteLength).toEqual(0)
expect(new Uint8Array(buffer).byteLength).toEqual(0)
})
testOrSkip('allows to read a text body as ArrayBuffer', async () => {
const response = new Response('Hello world')
const encoder = new TextEncoder()
const decoder = new TextDecoder()
const value = await response.arrayBuffer()
const decoded = decoder.decode(value)
expect(decoded).toEqual('Hello world')
expect(value).toEqual(encoder.encode('Hello world').buffer)
})
testOrSkip('allows to read a chunked body as ArrayBuffer', async () => {
const { readable, writable } = new TransformStream()
const encoder = new TextEncoder()
const writer = writable.getWriter()
void writer.write(encoder.encode('Hello '))
void writer.write(encoder.encode('world!'))
void writer.close()
const response = new Response(readable)
const value = await response.arrayBuffer()
const decoder = new TextDecoder()
const decoded = decoder.decode(value)
expect(decoded).toEqual('Hello world!')
expect(value).toEqual(encoder.encode('Hello world!').buffer)
})
testOrSkip('should pend stream data before getReader is called', async () => {
let startPulling = false
const encoder = new TextEncoder()
const decoder = new TextDecoder()
const readable = new ReadableStream({
start(controller) {
// delay streaming enqueue to trigger pulling
setTimeout(() => {
controller.enqueue(encoder.encode('hello'))
controller.enqueue(encoder.encode('world'))
}, 500)
},
pull() {
startPulling = true
},
})
expect(startPulling).toBe(false)
const reader = readable.getReader()
// Delay timer to trigger pulling
await new Promise((resolve) => setTimeout(resolve, 500))
// pulling should start after getReader is called
expect(startPulling).toBe(true)
let result = await reader.read()
expect(decoder.decode(result.value)).toBe('hello')
result = await reader.read()
expect(decoder.decode(result.value)).toBe('world')
})
testOrSkip('allows to read a URLSearchParams body as FormData', async () => {
const params = new URLSearchParams('q=URLUtils.searchParams&topic=api')
const response = new Response(params)
const formData = await response.formData()
expect(formData.get('topic')).toEqual('api')
})
testOrSkip('allows to read a Blob body as Blob', async () => {
const object = { hello: 'world' }
const str = JSON.stringify(object, null, 2)
const response = new Response(new Blob([str]))
const blob = await response.blob()
const txt = await blob.text()
expect(txt).toEqual(str)
})
testOrSkip('allows to read a text body as JSON', async () => {
const response = new Response(JSON.stringify({ message: 'hi', value: 10 }))
const value = await response.json()
expect(value).toEqual({ message: 'hi', value: 10 })
})
testOrSkip(
'throws when reading a text body as JSON but it is invalid',
async () => {
expect.assertions(2)
const response = new Response('{ hi: "there", ')
const error = await response.json().catch((err) => err)
expectErrorInstanceOf(error, SyntaxError)
expect(error.message).toContain(' in JSON at position 2')
},
)
testOrSkip('streams Uint8Array that can be decoded into a string', async () => {
const response = await fetch('https://example.vercel.sh')
const reader = response.body!.getReader()
let value: string = ''
const decoder = new TextDecoder()
while (true) {
const { done, value: chunk } = await reader.read()
if (done) {
break
}
value += decoder.decode(chunk)
}
expect(value).toContain('Example Domain')
})
const expectErrorInstanceOf = (error: Error, ctx: any) => {
if (globalThis.EdgeRuntime !== undefined) {
expect(error).toBeInstanceOf(ctx)
} else {
// https://github.com/jestjs/jest/issues/2549
expect(error.name).toBe(ctx.name)
}
}