forked from rails/request.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfetch_request.js
333 lines (281 loc) · 14 KB
/
fetch_request.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
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
/**
* @jest-environment jsdom
*/
import 'isomorphic-fetch'
import { FetchRequest } from '../src/fetch_request'
import { FetchResponse } from '../src/fetch_response'
jest.mock('../src/lib/utils', () => {
const originalModule = jest.requireActual('../src/lib/utils')
return {
__esModule: true,
...originalModule,
getCookie: jest.fn().mockReturnValue('mock-csrf-token'),
metaContent: jest.fn()
}
})
describe('perform', () => {
test('request is performed with 200', async () => {
const mockResponse = new Response("success!", { status: 200 })
window.fetch = jest.fn().mockResolvedValue(mockResponse)
const testRequest = new FetchRequest("get", "localhost")
const testResponse = await testRequest.perform()
expect(window.fetch).toHaveBeenCalledTimes(1)
expect(window.fetch).toHaveBeenCalledWith("localhost", testRequest.fetchOptions)
expect(testResponse).toStrictEqual(new FetchResponse(mockResponse))
})
test('request is performed with 401', async () => {
const mockResponse = new Response(undefined, { status: 401, headers: {'WWW-Authenticate': 'https://localhost/login'}})
window.fetch = jest.fn().mockResolvedValue(mockResponse)
delete window.location
window.location = new URL('https://www.example.com')
expect(window.location.href).toBe('https://www.example.com/')
const testRequest = new FetchRequest("get", "https://localhost")
expect(testRequest.perform()).rejects.toBe('https://localhost/login')
testRequest.perform().catch(() => {
expect(window.location.href).toBe('https://localhost/login')
})
})
test('turbo stream request automatically calls renderTurboStream when status is ok', async () => {
const mockResponse = new Response('', { status: 200, headers: { 'Content-Type': 'text/vnd.turbo-stream.html' }})
window.fetch = jest.fn().mockResolvedValue(mockResponse)
jest.spyOn(FetchResponse.prototype, "ok", "get").mockReturnValue(true)
jest.spyOn(FetchResponse.prototype, "isTurboStream", "get").mockReturnValue(true)
const renderSpy = jest.spyOn(FetchResponse.prototype, "renderTurboStream").mockImplementation()
const testRequest = new FetchRequest("get", "localhost")
await testRequest.perform()
expect(renderSpy).toHaveBeenCalledTimes(1)
jest.clearAllMocks();
})
test('turbo stream request automatically calls renderTurboStream when status is unprocessable entity', async () => {
const mockResponse = new Response('', { status: 422, headers: { 'Content-Type': 'text/vnd.turbo-stream.html' }})
window.fetch = jest.fn().mockResolvedValue(mockResponse)
jest.spyOn(FetchResponse.prototype, "ok", "get").mockReturnValue(true)
jest.spyOn(FetchResponse.prototype, "isTurboStream", "get").mockReturnValue(true)
const renderSpy = jest.spyOn(FetchResponse.prototype, "renderTurboStream").mockImplementation()
const testRequest = new FetchRequest("get", "localhost")
await testRequest.perform()
expect(renderSpy).toHaveBeenCalledTimes(1)
jest.clearAllMocks();
})
test('script request automatically calls activeScript', async () => {
const mockResponse = new Response('', { status: 200, headers: { 'Content-Type': 'application/javascript' }})
window.fetch = jest.fn().mockResolvedValue(mockResponse)
jest.spyOn(FetchResponse.prototype, "ok", "get").mockReturnValue(true)
jest.spyOn(FetchResponse.prototype, "isScript", "get").mockReturnValue(true)
const renderSpy = jest.spyOn(FetchResponse.prototype, "activeScript").mockImplementation()
const testRequest = new FetchRequest("get", "localhost")
await testRequest.perform()
expect(renderSpy).toHaveBeenCalledTimes(1)
jest.clearAllMocks();
})
})
test('treat method name case-insensitive', async () => {
const methodNames = [ "gEt", "GeT", "get", "GET"]
for (const methodName of methodNames) {
const testRequest = new FetchRequest(methodName, "localhost")
expect(testRequest.fetchOptions.method).toBe("GET")
}
})
test('casts URL to String', async () => {
const testRequest = new FetchRequest("GET", new URL("http://localhost"))
expect(typeof testRequest.originalUrl).toBe("string")
})
describe('header handling', () => {
const defaultHeaders = {
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-Token': 'mock-csrf-token',
'Accept': 'text/html, application/xhtml+xml'
}
describe('responseKind', () => {
test('none', async () => {
const defaultRequest = new FetchRequest("get", "localhost")
expect(defaultRequest.fetchOptions.headers)
.toStrictEqual(defaultHeaders)
})
test('html', async () => {
const htmlRequest = new FetchRequest("get", "localhost", { responseKind: 'html' })
expect(htmlRequest.fetchOptions.headers)
.toStrictEqual(defaultHeaders)
})
test('json', async () => {
const jsonRequest = new FetchRequest("get", "localhost", { responseKind: 'json' })
expect(jsonRequest.fetchOptions.headers)
.toStrictEqual({...defaultHeaders, 'Accept' : 'application/json, application/vnd.api+json'})
})
test('turbo-stream', async () => {
const turboRequest = new FetchRequest("get", "localhost", { responseKind: 'turbo-stream' })
expect(turboRequest.fetchOptions.headers)
.toStrictEqual({...defaultHeaders, 'Accept' : 'text/vnd.turbo-stream.html, text/html, application/xhtml+xml'})
})
test('invalid', async () => {
const invalidResponseKindRequest = new FetchRequest("get", "localhost", { responseKind: 'exotic' })
expect(invalidResponseKindRequest.fetchOptions.headers)
.toStrictEqual({...defaultHeaders, 'Accept' : '*/*'})
})
})
describe('contentType', () => {
test('is added to headers', () => {
const customRequest = new FetchRequest("get", "localhost/test.json", { contentType: 'any/thing' })
expect(customRequest.fetchOptions.headers)
.toStrictEqual({ ...defaultHeaders, "Content-Type": 'any/thing'})
})
test('is not set by formData', () => {
const formData = new FormData()
formData.append("this", "value")
const formDataRequest = new FetchRequest("get", "localhost", { body: formData })
expect(formDataRequest.fetchOptions.headers)
.toStrictEqual(defaultHeaders)
})
test('is set by file body', () => {
const file = new File(["contenxt"], "file.txt", { type: "text/plain" })
const fileRequest = new FetchRequest("get", "localhost", { body: file })
expect(fileRequest.fetchOptions.headers)
.toStrictEqual({ ...defaultHeaders, "Content-Type": "text/plain"})
})
test('is set by json body', () => {
const jsonRequest = new FetchRequest("get", "localhost", { body: { some: "json"} })
expect(jsonRequest.fetchOptions.headers)
.toStrictEqual({ ...defaultHeaders, "Content-Type": "application/json"})
})
})
test('additional headers are appended', () => {
const request = new FetchRequest("get", "localhost", { contentType: "application/json", headers: { custom: "Header" } })
expect(request.fetchOptions.headers)
.toStrictEqual({ ...defaultHeaders, custom: "Header", "Content-Type": "application/json"})
request.addHeader("test", "header")
expect(request.fetchOptions.headers)
.toStrictEqual({ ...defaultHeaders, custom: "Header", "Content-Type": "application/json", "test": "header"})
})
test('headers win over contentType', () => {
const request = new FetchRequest("get", "localhost", { contentType: "application/json", headers: { "Content-Type": "this/overwrites" } })
expect(request.fetchOptions.headers)
.toStrictEqual({ ...defaultHeaders, "Content-Type": "this/overwrites"})
})
test('serializes JSON to String', () => {
const jsonBody = { some: "json" }
let request
request = new FetchRequest("get", "localhost", { body: jsonBody, contentType: "application/json" })
expect(request.fetchOptions.body).toBe(JSON.stringify(jsonBody))
request = new FetchRequest("get", "localhost", { body: jsonBody })
expect(request.fetchOptions.body).toBe(JSON.stringify(jsonBody))
})
test('not serializes JSON with explicit different contentType', () => {
const jsonBody = { some: "json" }
const request = new FetchRequest("get", "localhost", { body: jsonBody, contentType: "not/json" })
expect(request.fetchOptions.body).toBe(jsonBody)
})
test('set redirect', () => {
let request
const redirectTypes = [ "follow", "error", "manual" ]
for (const redirect of redirectTypes) {
request = new FetchRequest("get", "localhost", { redirect })
expect(request.fetchOptions.redirect).toBe(redirect)
}
request = new FetchRequest("get", "localhost")
expect(request.fetchOptions.redirect).toBe("follow")
})
test('sets signal', () => {
let request
request = new FetchRequest("get", "localhost")
expect(request.fetchOptions.signal).toBe(undefined)
request = new FetchRequest("get", "localhost", { signal: "signal"})
expect(request.fetchOptions.signal).toBe("signal")
})
test('has credentials setting which can be changed', () => {
let request
request = new FetchRequest("get", "localhost")
expect(request.fetchOptions.credentials).toBe('same-origin')
request = new FetchRequest("get", "localhost", { credentials: "include"})
expect(request.fetchOptions.credentials).toBe('include')
})
describe('csrf token inclusion', () => {
// window.location.hostname is "localhost" in the test suite
test('csrf token is not included in headers if url hostname is not the same as window.location (http)', () => {
const request = new FetchRequest("get", "http://removeservice.com/test.json")
expect(request.fetchOptions.headers).not.toHaveProperty("X-CSRF-Token")
})
test('csrf token is not included in headers if url hostname is not the same as window.location (https)', () => {
const request = new FetchRequest("get", "https://removeservice.com/test.json")
expect(request.fetchOptions.headers).not.toHaveProperty("X-CSRF-Token")
})
test('csrf token is included in headers if url hostname is the same as window.location', () => {
const request = new FetchRequest("get", "http://localhost/test.json")
expect(request.fetchOptions.headers).toHaveProperty("X-CSRF-Token")
})
test('csrf token is included if url is a realative path', async () => {
const defaultRequest = new FetchRequest("get", "/somepath")
expect(defaultRequest.fetchOptions.headers).toHaveProperty("X-CSRF-Token")
})
test('csrf token is included if url is not parseable', async () => {
const defaultRequest = new FetchRequest("get", "not-a-url")
expect(defaultRequest.fetchOptions.headers).toHaveProperty("X-CSRF-Token")
})
})
})
describe('query params are parsed', () => {
test('anchors are rejected', () => {
const mixedRequest = new FetchRequest("post", "localhost/test?a=1&b=2#anchor", { query: { c: 3 } })
expect(mixedRequest.url).toBe("localhost/test?a=1&b=2&c=3")
const queryRequest = new FetchRequest("post", "localhost/test?a=1&b=2&c=3#anchor")
expect(queryRequest.url).toBe("localhost/test?a=1&b=2&c=3")
const optionsRequest = new FetchRequest("post", "localhost/test#anchor", { query: { a: 1, b: 2, c: 3 } })
expect(optionsRequest.url).toBe("localhost/test?a=1&b=2&c=3")
})
test('url and options are merged', () => {
const urlAndOptionRequest = new FetchRequest("post", "localhost/test?a=1&b=2", { query: { c: 3 } })
expect(urlAndOptionRequest.url).toBe("localhost/test?a=1&b=2&c=3")
})
test('only url', () => {
const urlRequest = new FetchRequest("post", "localhost/test?a=1&b=2")
expect(urlRequest.url).toBe("localhost/test?a=1&b=2")
})
test('only options', () => {
const optionRequest = new FetchRequest("post", "localhost/test", { query: { c: 3 } })
expect(optionRequest.url).toBe("localhost/test?c=3")
})
test('options accept formData', () => {
const formData = new FormData()
formData.append("a", 1)
const urlAndOptionRequest = new FetchRequest("post", "localhost/test", { query: formData })
expect(urlAndOptionRequest.url).toBe("localhost/test?a=1")
})
test('options accept urlSearchParams', () => {
const urlSearchParams = new URLSearchParams()
urlSearchParams.append("a", 1)
const urlAndOptionRequest = new FetchRequest("post", "localhost/test", { query: urlSearchParams })
expect(urlAndOptionRequest.url).toBe("localhost/test?a=1")
})
test('urlSearchParams with list entries', () => {
const urlSearchParams = new URLSearchParams()
urlSearchParams.append("a[]", 1)
urlSearchParams.append("a[]", 2)
const urlAndOptionRequest = new FetchRequest("post", "localhost/test", {query: urlSearchParams})
expect(urlAndOptionRequest.url).toBe("localhost/test?a%5B%5D=1&a%5B%5D=2")
});
test('handles empty query', () => {
const emptyQueryRequest = new FetchRequest("get", "localhost/test")
expect(emptyQueryRequest.url).toBe("localhost/test")
})
})
describe('turbostream', () => {
test('turbo fetch is called for turbo-stream responseKind', async() => {
const mockResponse = new Response("success!", { status: 200 })
window.fetch = jest.fn().mockResolvedValue(mockResponse)
window.Turbo = { fetch: jest.fn().mockResolvedValue(mockResponse) }
const testRequest = new FetchRequest("get", "localhost", { responseKind: 'turbo-stream' })
const testResponse = await testRequest.perform()
expect(window.Turbo.fetch).toHaveBeenCalledTimes(1)
expect(window.fetch).toHaveBeenCalledTimes(0)
expect(testResponse).toStrictEqual(new FetchResponse(mockResponse))
})
test('turbo fetch is called for other responseKind', async() => {
const mockResponse = new Response("success!", { status: 200 })
window.fetch = jest.fn().mockResolvedValue(mockResponse)
window.Turbo = { fetch: jest.fn().mockResolvedValue(mockResponse) }
const testRequest = new FetchRequest("get", "localhost")
const testResponse = await testRequest.perform()
expect(window.Turbo.fetch).toHaveBeenCalledTimes(0)
expect(window.fetch).toHaveBeenCalledTimes(1)
expect(testResponse).toStrictEqual(new FetchResponse(mockResponse))
})
})