-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
index.test.ts
655 lines (573 loc) · 19.4 KB
/
index.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
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
import { until } from '@vueuse/shared'
import { ref } from 'vue-demi'
import { retry } from '../../.test'
import { createFetch, useFetch } from '.'
import '../../.test/mockServer'
const jsonMessage = { hello: 'world' }
const jsonUrl = `https://example.com?json=${encodeURI(JSON.stringify(jsonMessage))}`
// Listen to make sure fetch is actually called.
// Use msw to stub out the req/res
let fetchSpy = vitest.spyOn(window, 'fetch')
let onFetchErrorSpy = vitest.fn()
let onFetchResponseSpy = vitest.fn()
let onFetchFinallySpy = vitest.fn()
const fetchSpyHeaders = (idx = 0) => fetchSpy.mock.calls[idx][1]!.headers
describe('useFetch', () => {
beforeEach(() => {
fetchSpy = vitest.spyOn(window, 'fetch')
onFetchErrorSpy = vitest.fn()
onFetchResponseSpy = vitest.fn()
onFetchFinallySpy = vitest.fn()
})
test('should have status code of 200 and message of Hello World', async () => {
const { statusCode, data } = useFetch('https://example.com?text=hello')
await retry(() => {
expect(fetchSpy).toHaveBeenCalledOnce()
expect(data.value).toBe('hello')
expect(statusCode.value).toBe(200)
})
})
test('should be able to use the Headers object', async () => {
const myHeaders = new Headers()
myHeaders.append('Authorization', 'test')
useFetch('https://example.com/', { headers: myHeaders })
await retry(() => {
expect(fetchSpyHeaders()).toEqual({ authorization: 'test' })
})
})
test('should parse response as json', async () => {
const { data } = useFetch(jsonUrl).json()
await retry(() => {
expect(data.value).toEqual(jsonMessage)
})
})
test('should use custom fetch', async () => {
let count = 0
await useFetch('https://example.com/', {
fetch(input, init) {
count = 1
return window.fetch(input, init)
},
})
expect(count).toEqual(1)
})
it('should use custom payloadType', async () => {
let options: any
useFetch('https://example.com', {
beforeFetch: (ctx) => {
options = ctx.options
},
}).post({ x: 1 }, 'unknown')
await retry(() => {
expect(fetchSpy).toHaveBeenCalledOnce()
expect(options.body).toEqual({ x: 1 })
expect(options.headers['Content-Type']).toBe('unknown')
})
})
test('should have an error on 400', async () => {
const { error, statusCode } = useFetch('https://example.com?status=400')
await retry(() => {
expect(statusCode.value).toBe(400)
expect(error.value).toBe('Bad Request')
})
})
test('should throw error', async () => {
const error1 = await useFetch('https://example.com?status=400').execute(true).catch(err => err)
const error2 = await useFetch('https://example.com?status=600').execute(true).catch(err => err)
expect(error1.name).toBe('Error')
expect(error1.message).toBe('Bad Request')
expect(error2.name).toBe('Error')
expect(error2.message).toBe('')
})
test('should abort request and set aborted to true', async () => {
const { aborted, abort, execute } = useFetch('https://example.com')
setTimeout(() => abort(), 0)
await retry(() => expect(aborted.value).toBe(true))
execute()
setTimeout(() => abort(), 0)
await retry(() => expect(aborted.value).toBe(true))
})
test('should not call if immediate is false', async () => {
useFetch('https://example.com', { immediate: false })
await retry(() => expect(fetchSpy).toBeCalledTimes(0))
})
test('should refetch if refetch is set to true', async () => {
const url = ref('https://example.com')
useFetch(url, { refetch: true })
url.value = 'https://example.com?text'
await retry(() => expect(fetchSpy).toBeCalledTimes(2))
})
test('should auto refetch when the refetch is set to true and the payload is a ref', async () => {
const param = ref({ num: 1 })
useFetch('https://example.com', { refetch: true }).post(param)
param.value.num = 2
await retry(() => expect(fetchSpy).toBeCalledTimes(2))
})
test('should create an instance of useFetch with baseUrls', async () => {
const fetchHeaders = { Authorization: 'test' }
const requestHeaders = { 'Accept-Language': 'en-US' }
const allHeaders = { ...fetchHeaders, ...requestHeaders }
const useMyFetchWithBaseUrl = createFetch({ baseUrl: 'https://example.com', fetchOptions: { headers: fetchHeaders } })
const useMyFetchWithoutBaseUrl = createFetch({ fetchOptions: { headers: fetchHeaders } })
useMyFetchWithBaseUrl('test', { headers: requestHeaders })
useMyFetchWithBaseUrl('/test', { headers: requestHeaders })
useMyFetchWithoutBaseUrl('https://example.com/test', { headers: requestHeaders })
await retry(() => {
expect(fetchSpy).toHaveBeenCalledTimes(3)
expect(fetchSpy).toHaveBeenNthCalledWith(1, 'https://example.com/test', expect.anything())
expect(fetchSpy).toHaveBeenNthCalledWith(2, 'https://example.com/test', expect.anything())
expect(fetchSpy).toHaveBeenNthCalledWith(3, 'https://example.com/test', expect.anything())
expect(fetchSpyHeaders()).toMatchObject(allHeaders)
})
})
test('should chain beforeFetch function when using a factory instance', async () => {
const useMyFetch = createFetch({
baseUrl: 'https://example.com',
options: {
beforeFetch({ options }) {
options.headers = { ...options.headers, Global: 'foo' }
return { options }
},
},
})
useMyFetch('test', {
beforeFetch({ options }) {
options.headers = { ...options.headers, Local: 'foo' }
return { options }
},
})
await retry(() => {
expect(fetchSpyHeaders()).toMatchObject({ Global: 'foo', Local: 'foo' })
})
})
test('should chain afterFetch function when using a factory instance', async () => {
const useMyFetch = createFetch({
baseUrl: 'https://example.com',
options: {
afterFetch(ctx) {
ctx.data.title = 'Global'
return ctx
},
},
})
const { data } = useMyFetch('test?json', {
afterFetch(ctx) {
ctx.data.title += ' Local'
return ctx
},
}).json()
await retry(() => {
expect(data.value).toEqual(expect.objectContaining({ title: 'Global Local' }))
})
})
test('should chain onFetchError function when using a factory instance', async () => {
const useMyFetch = createFetch({
baseUrl: 'https://example.com',
options: {
onFetchError(ctx) {
ctx.data.title = 'Global'
return ctx
},
},
})
const { data } = useMyFetch('test?status=400&json', {
onFetchError(ctx) {
ctx.data.title += ' Local'
return ctx
},
}).json()
await retry(() => {
expect(data.value).toEqual(expect.objectContaining({ title: 'Global Local' }))
})
})
test('should chain beforeFetch function when using a factory instance and the options object in useMyFetch', async () => {
const useMyFetch = createFetch({
baseUrl: 'https://example.com',
options: {
beforeFetch({ options }) {
options.headers = { ...options.headers, Global: 'foo' }
return { options }
},
},
})
useMyFetch(
'test',
{ method: 'GET' },
{
beforeFetch({ options }) {
options.headers = { ...options.headers, Local: 'foo' }
return { options }
},
})
await retry(() => {
expect(fetchSpyHeaders()).toMatchObject({ Global: 'foo', Local: 'foo' })
})
})
test('should chain afterFetch function when using a factory instance and the options object in useMyFetch', async () => {
const useMyFetch = createFetch({
baseUrl: 'https://example.com',
options: {
afterFetch(ctx) {
ctx.data.title = 'Global'
return ctx
},
},
})
const { data } = useMyFetch(
'test?json',
{ method: 'GET' },
{
afterFetch(ctx) {
ctx.data.title += ' Local'
return ctx
},
}).json()
await retry(() => {
expect(data.value).toEqual(expect.objectContaining({ title: 'Global Local' }))
})
})
test('should chain onFetchError function when using a factory instance and the options object in useMyFetch', async () => {
const useMyFetch = createFetch({
baseUrl: 'https://example.com',
options: {
onFetchError(ctx) {
ctx.data.title = 'Global'
return ctx
},
},
})
const { data } = useMyFetch(
'test?status=400&json',
{ method: 'GET' },
{
onFetchError(ctx) {
ctx.data.title += ' Local'
return ctx
},
}).json()
await retry(() => {
expect(data.value).toEqual(expect.objectContaining({ title: 'Global Local' }))
})
})
test('should overwrite beforeFetch function when using a factory instance', async () => {
const useMyFetch = createFetch({
baseUrl: 'https://example.com',
combination: 'overwrite',
options: {
beforeFetch({ options }) {
options.headers = { ...options.headers, Global: 'foo' }
return { options }
},
},
})
useMyFetch('test', {
beforeFetch({ options }) {
options.headers = { ...options.headers, Local: 'foo' }
return { options }
},
})
await retry(() => {
expect(fetchSpyHeaders()).toMatchObject({ Local: 'foo' })
})
})
test('should overwrite afterFetch function when using a factory instance', async () => {
const useMyFetch = createFetch({
baseUrl: 'https://example.com',
combination: 'overwrite',
options: {
afterFetch(ctx) {
ctx.data.global = 'Global'
return ctx
},
},
})
const { data } = useMyFetch('test?json', {
afterFetch(ctx) {
ctx.data.local = 'Local'
return ctx
},
}).json()
await retry(() => {
expect(data.value).toEqual(expect.objectContaining({ local: 'Local' }))
expect(data.value).toEqual(expect.not.objectContaining({ global: 'Global' }))
})
})
test('should overwrite onFetchError function when using a factory instance', async () => {
const useMyFetch = createFetch({
baseUrl: 'https://example.com',
combination: 'overwrite',
options: {
onFetchError(ctx) {
ctx.data.global = 'Global'
return ctx
},
},
})
const { data } = useMyFetch('test?status=400&json', {
onFetchError(ctx) {
ctx.data.local = 'Local'
return ctx
},
}).json()
await retry(() => {
expect(data.value).toEqual(expect.objectContaining({ local: 'Local' }))
expect(data.value).toEqual(expect.not.objectContaining({ global: 'Global' }))
})
})
test('should overwrite beforeFetch function when using a factory instance and the options object in useMyFetch', async () => {
const useMyFetch = createFetch({
baseUrl: 'https://example.com',
combination: 'overwrite',
options: {
beforeFetch({ options }) {
options.headers = { ...options.headers, Global: 'foo' }
return { options }
},
},
})
useMyFetch(
'test',
{ method: 'GET' },
{
beforeFetch({ options }) {
options.headers = { ...options.headers, Local: 'foo' }
return { options }
},
})
await retry(() => {
expect(fetchSpyHeaders()).toMatchObject({ Local: 'foo' })
})
})
test('should overwrite afterFetch function when using a factory instance and the options object in useMyFetch', async () => {
const useMyFetch = createFetch({
baseUrl: 'https://example.com',
combination: 'overwrite',
options: {
afterFetch(ctx) {
ctx.data.global = 'Global'
return ctx
},
},
})
const { data } = useMyFetch(
'test?json',
{ method: 'GET' },
{
afterFetch(ctx) {
ctx.data.local = 'Local'
return ctx
},
}).json()
await retry(() => {
expect(data.value).toEqual(expect.objectContaining({ local: 'Local' }))
expect(data.value).toEqual(expect.not.objectContaining({ global: 'Global' }))
})
})
test('should overwrite onFetchError function when using a factory instance and the options object in useMyFetch', async () => {
const useMyFetch = createFetch({
baseUrl: 'https://example.com',
combination: 'overwrite',
options: {
onFetchError(ctx) {
ctx.data.global = 'Global'
return ctx
},
},
})
const { data } = useMyFetch(
'test?status=400&json',
{ method: 'GET' },
{
onFetchError(ctx) {
ctx.data.local = 'Local'
return ctx
},
}).json()
await retry(() => {
expect(data.value).toEqual(expect.objectContaining({ local: 'Local' }))
expect(data.value).toEqual(expect.not.objectContaining({ global: 'Global' }))
})
})
test('should run the beforeFetch function and add headers to the request', async () => {
useFetch('https://example.com', { headers: { 'Accept-Language': 'en-US' } }, {
beforeFetch({ options }) {
options.headers = {
...options.headers,
Authorization: 'my-auth-token',
}
return { options }
},
})
await retry(() => {
expect(fetchSpyHeaders()).toMatchObject({ 'Authorization': 'my-auth-token', 'Accept-Language': 'en-US' })
})
})
test('should run the beforeFetch has default headers', async () => {
useFetch('https://example.com', {
beforeFetch({ options }) {
expect(options.headers).toBeDefined()
return { options }
},
})
})
test('should run the beforeFetch function and cancel the request', async () => {
const { execute } = useFetch('https://example.com', {
immediate: false,
beforeFetch({ cancel }) {
cancel()
},
})
await execute()
expect(fetchSpy).toBeCalledTimes(0)
})
test('should run the afterFetch function', async () => {
const { data } = useFetch(jsonUrl, {
afterFetch(ctx) {
ctx.data.title = 'Hunter x Hunter'
return ctx
},
}).json()
await retry(() => {
expect(data.value).toEqual(expect.objectContaining({ title: 'Hunter x Hunter' }))
})
})
test('async chained beforeFetch and afterFetch should be executed in order', async () => {
const sleep = (delay: number) => new Promise(resolve => setTimeout(resolve, delay))
const useMyFetch = createFetch({
baseUrl: 'https://example.com',
options: {
async beforeFetch({ options }) {
await sleep(50)
options.headers = { ...options.headers, title: 'Hunter X Hunter' }
return { options }
},
async afterFetch(ctx) {
await sleep(50)
ctx.data.message = 'Hunter X Hunter'
return ctx
},
},
})
const { data } = await useMyFetch(
'test?json',
{ method: 'GET' },
{
async beforeFetch({ options }) {
await Promise.resolve()
options.headers = { ...options.headers, title: 'Hello, VueUse' }
return { options }
},
async afterFetch(ctx) {
await Promise.resolve()
ctx.data.message = 'Hello, VueUse'
return ctx
},
},
).json()
await retry(() => {
expect(fetchSpyHeaders()).toMatchObject({ title: 'Hello, VueUse' })
expect(data.value).toEqual(expect.objectContaining({ message: 'Hello, VueUse' }))
})
})
test('should run the onFetchError function', async () => {
const { data, statusCode } = useFetch('https://example.com?status=400&json', {
onFetchError(ctx) {
ctx.data.title = 'Hunter x Hunter'
return ctx
},
}).json()
await retry(() => {
expect(statusCode.value).toEqual(400)
expect(data.value).toEqual(expect.objectContaining({ title: 'Hunter x Hunter' }))
})
})
test('should run the onFetchError function when network error', async () => {
const { data, statusCode } = useFetch('https://example.com?status=500&text=Internal%20Server%20Error', {
onFetchError(ctx) {
ctx.data = { title: 'Hunter x Hunter' }
return ctx
},
}).json()
await retry(() => {
expect(statusCode.value).toStrictEqual(500)
expect(data.value).toEqual({ title: 'Hunter x Hunter' })
})
})
test('should emit onFetchResponse event', async () => {
const onResponseSpy = vitest.fn()
const { onFetchResponse } = useFetch('https://example.com')
onFetchResponse(onResponseSpy)
await retry(() => {
expect(onResponseSpy).toHaveBeenCalledOnce()
})
})
test('should emit onFetchResponse event', async () => {
const { onFetchResponse, onFetchError, onFetchFinally } = useFetch('https://example.com')
onFetchResponse(onFetchResponseSpy)
onFetchError(onFetchErrorSpy)
onFetchFinally(onFetchFinallySpy)
await retry(() => {
expect(onFetchErrorSpy).not.toHaveBeenCalled()
expect(onFetchResponseSpy).toHaveBeenCalled()
expect(onFetchFinallySpy).toHaveBeenCalled()
})
})
test('should emit onFetchError event', async () => {
const { onFetchError, onFetchFinally, onFetchResponse } = useFetch('https://example.com?status=400')
onFetchError(onFetchErrorSpy)
onFetchResponse(onFetchResponseSpy)
onFetchFinally(onFetchFinallySpy)
await retry(() => {
expect(onFetchErrorSpy).toHaveBeenCalled()
expect(onFetchResponseSpy).not.toHaveBeenCalled()
expect(onFetchFinallySpy).toHaveBeenCalled()
})
})
test('setting the request method w/ get and return type w/ json', async () => {
const { data } = useFetch(jsonUrl).get().json()
await retry(() => expect(data.value).toEqual(jsonMessage))
})
test('setting the request method w/ post and return type w/ text', async () => {
const { data } = useFetch(jsonUrl).post().text()
await retry(() => expect(data.value).toEqual(JSON.stringify(jsonMessage)))
})
test('allow setting response type before doing request', async () => {
const shell = useFetch(jsonUrl, {
immediate: false,
}).get().text()
shell.json()
shell.execute()
await retry(() => expect(shell.data.value).toEqual(jsonMessage))
})
test('not allowed setting request method and response type while doing request', async () => {
const shell = useFetch(jsonUrl).get().text()
const { isFetching, data } = shell
await until(isFetching).toBe(true)
shell.post()
shell.json()
await retry(() => {
expect(fetchSpy).toHaveBeenCalledOnce()
expect(data.value).toEqual(JSON.stringify(jsonMessage))
})
})
test('should abort request when timeout reached', async () => {
const { aborted, execute } = useFetch('https://example.com?delay=100', { timeout: 10 })
await retry(() => expect(aborted.value).toBeTruthy())
await execute()
await retry(() => expect(aborted.value).toBeTruthy())
})
test('should not abort request when timeout is not reached', async () => {
const { data } = useFetch(jsonUrl, { timeout: 100 }).json()
await retry(() => expect(data.value).toEqual(jsonMessage))
})
test('should await request', async () => {
const { data } = await useFetch(jsonUrl).get()
expect(data.value).toEqual(JSON.stringify(jsonMessage))
expect(fetchSpy).toBeCalledTimes(1)
})
test('should await json response', async () => {
const { data } = await useFetch(jsonUrl).json()
expect(data.value).toEqual(jsonMessage)
expect(fetchSpy).toBeCalledTimes(1)
})
})