forked from TanStack/query
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquery.test.tsx
888 lines (701 loc) · 21.8 KB
/
query.test.tsx
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
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
import {
sleep,
queryKey,
mockVisibilityState,
mockLogger,
createQueryClient,
} from '../../../../tests/utils'
import {
QueryCache,
QueryClient,
QueryObserver,
isCancelledError,
isError,
onlineManager,
QueryFunctionContext,
QueryObserverResult,
} from '..'
import { waitFor } from '@testing-library/react'
describe('query', () => {
let queryClient: QueryClient
let queryCache: QueryCache
beforeEach(() => {
queryClient = createQueryClient()
queryCache = queryClient.getQueryCache()
queryClient.mount()
})
afterEach(() => {
queryClient.clear()
})
test('should use the longest cache time it has seen', async () => {
const key = queryKey()
await queryClient.prefetchQuery(key, () => 'data', {
cacheTime: 100,
})
await queryClient.prefetchQuery(key, () => 'data', {
cacheTime: 200,
})
await queryClient.prefetchQuery(key, () => 'data', {
cacheTime: 10,
})
const query = queryCache.find(key)!
expect(query.cacheTime).toBe(200)
})
it('should continue retry after focus regain and resolve all promises', async () => {
const key = queryKey()
// make page unfocused
const visibilityMock = mockVisibilityState('hidden')
let count = 0
let result
const promise = queryClient.fetchQuery(
key,
async () => {
count++
if (count === 3) {
return `data${count}`
}
throw new Error(`error${count}`)
},
{
retry: 3,
retryDelay: 1,
},
)
promise.then((data) => {
result = data
})
// Check if we do not have a result
expect(result).toBeUndefined()
// Check if the query is really paused
await sleep(50)
expect(result).toBeUndefined()
// Reset visibilityState to original value
visibilityMock.mockRestore()
window.dispatchEvent(new FocusEvent('focus'))
// There should not be a result yet
expect(result).toBeUndefined()
// By now we should have a value
await sleep(50)
expect(result).toBe('data3')
})
it('should continue retry after reconnect and resolve all promises', async () => {
const key = queryKey()
onlineManager.setOnline(false)
let count = 0
let result
const promise = queryClient.fetchQuery(
key,
async () => {
count++
if (count === 3) {
return `data${count}`
}
throw new Error(`error${count}`)
},
{
retry: 3,
retryDelay: 1,
},
)
promise.then((data) => {
result = data
})
// Check if we do not have a result
expect(result).toBeUndefined()
// Check if the query is really paused
await sleep(50)
expect(result).toBeUndefined()
// Reset navigator to original value
onlineManager.setOnline(true)
// There should not be a result yet
expect(result).toBeUndefined()
// By now we should have a value
await sleep(50)
expect(result).toBe('data3')
})
it('should throw a CancelledError when a paused query is cancelled', async () => {
const key = queryKey()
// make page unfocused
const visibilityMock = mockVisibilityState('hidden')
let count = 0
let result
const promise = queryClient.fetchQuery(
key,
async (): Promise<unknown> => {
count++
throw new Error(`error${count}`)
},
{
retry: 3,
retryDelay: 1,
},
)
promise.catch((data) => {
result = data
})
const query = queryCache.find(key)!
// Check if the query is really paused
await sleep(50)
expect(result).toBeUndefined()
// Cancel query
query.cancel()
// Check if the error is set to the cancelled error
await sleep(0)
expect(isCancelledError(result)).toBe(true)
// Reset visibilityState to original value
visibilityMock.mockRestore()
window.dispatchEvent(new FocusEvent('focus'))
})
test('should provide context to queryFn', async () => {
const key = queryKey()
const queryFn = jest
.fn<
Promise<'data'>,
[QueryFunctionContext<ReturnType<typeof queryKey>>]
>()
.mockResolvedValue('data')
queryClient.prefetchQuery(key, queryFn)
await sleep(10)
expect(queryFn).toHaveBeenCalledTimes(1)
const args = queryFn.mock.calls[0]![0]
expect(args).toBeDefined()
expect(args.pageParam).toBeUndefined()
expect(args.queryKey).toEqual(key)
if (typeof AbortSignal === 'function') {
expect(args.signal).toBeInstanceOf(AbortSignal)
} else {
expect(args.signal).toBeUndefined()
}
})
test('should continue if cancellation is not supported and signal is not consumed', async () => {
const key = queryKey()
queryClient.prefetchQuery(key, async () => {
await sleep(100)
return 'data'
})
await sleep(10)
// Subscribe and unsubscribe to simulate cancellation because the last observer unsubscribed
const observer = new QueryObserver(queryClient, {
queryKey: key,
enabled: false,
})
const unsubscribe = observer.subscribe(() => undefined)
unsubscribe()
await sleep(100)
const query = queryCache.find(key)!
expect(query.state).toMatchObject({
data: 'data',
status: 'success',
dataUpdateCount: 1,
})
})
test('should not continue when last observer unsubscribed if the signal was consumed', async () => {
const key = queryKey()
queryClient.prefetchQuery(key, async ({ signal }) => {
await sleep(100)
return signal?.aborted ? 'aborted' : 'data'
})
await sleep(10)
// Subscribe and unsubscribe to simulate cancellation because the last observer unsubscribed
const observer = new QueryObserver(queryClient, {
queryKey: key,
enabled: false,
})
const unsubscribe = observer.subscribe(() => undefined)
unsubscribe()
await sleep(100)
const query = queryCache.find(key)!
if (typeof AbortSignal === 'function') {
expect(query.state).toMatchObject({
data: undefined,
status: 'loading',
fetchStatus: 'idle',
})
} else {
expect(query.state).toMatchObject({
data: 'data',
status: 'success',
fetchStatus: 'idle',
dataUpdateCount: 1,
})
}
})
test('should provide an AbortSignal to the queryFn that provides info about the cancellation state', async () => {
const key = queryKey()
const queryFn = jest.fn<
Promise<unknown>,
[QueryFunctionContext<ReturnType<typeof queryKey>>]
>()
const onAbort = jest.fn()
const abortListener = jest.fn()
let error
queryFn.mockImplementation(async ({ signal }) => {
if (signal) {
signal.onabort = onAbort
signal.addEventListener('abort', abortListener)
}
await sleep(10)
if (signal) {
signal.onabort = null
signal.removeEventListener('abort', abortListener)
}
throw new Error()
})
const promise = queryClient.fetchQuery(key, queryFn, {
retry: 3,
retryDelay: 10,
})
promise.catch((e) => {
error = e
})
const query = queryCache.find(key)!
expect(queryFn).toHaveBeenCalledTimes(1)
let signal = queryFn.mock.calls[0]![0].signal
if (typeof AbortSignal === 'function') {
signal = queryFn.mock.calls[0]![0].signal
expect(signal?.aborted).toBe(false)
}
expect(onAbort).not.toHaveBeenCalled()
expect(abortListener).not.toHaveBeenCalled()
query.cancel()
await sleep(100)
if (typeof AbortSignal === 'function') {
expect(signal?.aborted).toBe(true)
expect(onAbort).toHaveBeenCalledTimes(1)
expect(abortListener).toHaveBeenCalledTimes(1)
}
expect(isCancelledError(error)).toBe(true)
})
test('should not continue if explicitly cancelled', async () => {
const key = queryKey()
const queryFn = jest.fn<unknown, unknown[]>()
queryFn.mockImplementation(async () => {
await sleep(10)
throw new Error()
})
let error
const promise = queryClient.fetchQuery(key, queryFn, {
retry: 3,
retryDelay: 10,
})
promise.catch((e) => {
error = e
})
const query = queryCache.find(key)!
query.cancel()
await sleep(100)
expect(queryFn).toHaveBeenCalledTimes(1)
expect(isCancelledError(error)).toBe(true)
})
test('should not error if reset while loading', async () => {
const key = queryKey()
const queryFn = jest.fn<unknown, unknown[]>()
queryFn.mockImplementation(async () => {
await sleep(10)
throw new Error()
})
queryClient.fetchQuery(key, queryFn, {
retry: 3,
retryDelay: 10,
})
// Ensure the query is loading
const query = queryCache.find(key)!
expect(query.state.status).toBe('loading')
// Reset the query while it is loading
query.reset()
await sleep(100)
// The query should
expect(queryFn).toHaveBeenCalledTimes(1) // have been called,
expect(query.state.error).toBe(null) // not have an error, and
expect(query.state.fetchStatus).toBe('idle') // not be loading any longer
})
test('should be able to refetch a cancelled query', async () => {
const key = queryKey()
const queryFn = jest.fn<unknown, unknown[]>()
queryFn.mockImplementation(async () => {
await sleep(50)
return 'data'
})
queryClient.prefetchQuery(key, queryFn)
const query = queryCache.find(key)!
await sleep(10)
query.cancel()
await sleep(100)
expect(queryFn).toHaveBeenCalledTimes(1)
expect(isCancelledError(query.state.error)).toBe(true)
const result = await query.fetch()
expect(result).toBe('data')
expect(query.state.error).toBe(null)
expect(queryFn).toHaveBeenCalledTimes(2)
})
test('cancelling a resolved query should not have any effect', async () => {
const key = queryKey()
await queryClient.prefetchQuery(key, async () => 'data')
const query = queryCache.find(key)!
query.cancel()
await sleep(10)
expect(query.state.data).toBe('data')
})
test('cancelling a rejected query should not have any effect', async () => {
const key = queryKey()
await queryClient.prefetchQuery(key, async (): Promise<unknown> => {
throw new Error('error')
})
const query = queryCache.find(key)!
query.cancel()
await sleep(10)
expect(isError(query.state.error)).toBe(true)
expect(isCancelledError(query.state.error)).toBe(false)
})
test('the previous query status should be kept when refetching', async () => {
const key = queryKey()
await queryClient.prefetchQuery(key, () => 'data')
const query = queryCache.find(key)!
expect(query.state.status).toBe('success')
await queryClient.prefetchQuery(
key,
() => Promise.reject<string>('reject'),
{
retry: false,
},
)
expect(query.state.status).toBe('error')
queryClient.prefetchQuery(
key,
async () => {
await sleep(10)
return Promise.reject<unknown>('reject')
},
{ retry: false },
)
expect(query.state.status).toBe('error')
await sleep(100)
expect(query.state.status).toBe('error')
})
test('queries with cacheTime 0 should be removed immediately after unsubscribing', async () => {
const key = queryKey()
let count = 0
const observer = new QueryObserver(queryClient, {
queryKey: key,
queryFn: () => {
count++
return 'data'
},
cacheTime: 0,
staleTime: Infinity,
})
const unsubscribe1 = observer.subscribe(() => undefined)
unsubscribe1()
await waitFor(() => expect(queryCache.find(key)).toBeUndefined())
const unsubscribe2 = observer.subscribe(() => undefined)
unsubscribe2()
await waitFor(() => expect(queryCache.find(key)).toBeUndefined())
expect(count).toBe(1)
})
test('should be garbage collected when unsubscribed to', async () => {
const key = queryKey()
const observer = new QueryObserver(queryClient, {
queryKey: key,
queryFn: async () => 'data',
cacheTime: 0,
})
expect(queryCache.find(key)).toBeDefined()
const unsubscribe = observer.subscribe(() => undefined)
expect(queryCache.find(key)).toBeDefined()
unsubscribe()
await waitFor(() => expect(queryCache.find(key)).toBeUndefined())
})
test('should be garbage collected later when unsubscribed and query is fetching', async () => {
const key = queryKey()
const observer = new QueryObserver(queryClient, {
queryKey: key,
queryFn: async () => {
await sleep(20)
return 'data'
},
cacheTime: 10,
})
const unsubscribe = observer.subscribe(() => undefined)
await sleep(20)
expect(queryCache.find(key)).toBeDefined()
observer.refetch()
unsubscribe()
await sleep(10)
// unsubscribe should not remove even though cacheTime has elapsed b/c query is still fetching
expect(queryCache.find(key)).toBeDefined()
await sleep(10)
// should be removed after an additional staleTime wait
await waitFor(() => expect(queryCache.find(key)).toBeUndefined())
})
test('should not be garbage collected unless there are no subscribers', async () => {
const key = queryKey()
const observer = new QueryObserver(queryClient, {
queryKey: key,
queryFn: async () => 'data',
cacheTime: 0,
})
expect(queryCache.find(key)).toBeDefined()
const unsubscribe = observer.subscribe(() => undefined)
await sleep(100)
expect(queryCache.find(key)).toBeDefined()
unsubscribe()
await sleep(100)
expect(queryCache.find(key)).toBeUndefined()
queryClient.setQueryData(key, 'data')
await sleep(100)
expect(queryCache.find(key)).toBeDefined()
})
test('should return proper count of observers', async () => {
const key = queryKey()
const options = { queryKey: key, queryFn: async () => 'data' }
const observer = new QueryObserver(queryClient, options)
const observer2 = new QueryObserver(queryClient, options)
const observer3 = new QueryObserver(queryClient, options)
const query = queryCache.find(key)
expect(query?.getObserversCount()).toEqual(0)
const unsubscribe1 = observer.subscribe(() => undefined)
const unsubscribe2 = observer2.subscribe(() => undefined)
const unsubscribe3 = observer3.subscribe(() => undefined)
expect(query?.getObserversCount()).toEqual(3)
unsubscribe3()
expect(query?.getObserversCount()).toEqual(2)
unsubscribe2()
expect(query?.getObserversCount()).toEqual(1)
unsubscribe1()
expect(query?.getObserversCount()).toEqual(0)
})
test('stores meta object in query', async () => {
const meta = {
it: 'works',
}
const key = queryKey()
await queryClient.prefetchQuery(key, () => 'data', {
meta,
})
const query = queryCache.find(key)!
expect(query.meta).toBe(meta)
expect(query.options.meta).toBe(meta)
})
test('updates meta object on change', async () => {
const meta = {
it: 'works',
}
const key = queryKey()
const queryFn = () => 'data'
await queryClient.prefetchQuery(key, queryFn, {
meta,
})
await queryClient.prefetchQuery(key, queryFn, {
meta: undefined,
})
const query = queryCache.find(key)!
expect(query.meta).toBeUndefined()
expect(query.options.meta).toBeUndefined()
})
test('provides meta object inside query function', async () => {
const meta = {
it: 'works',
}
const queryFn = jest.fn(() => 'data')
const key = queryKey()
await queryClient.prefetchQuery(key, queryFn, {
meta,
})
expect(queryFn).toBeCalledWith(
expect.objectContaining({
meta,
}),
)
})
test('should refetch the observer when online method is called', async () => {
const key = queryKey()
const observer = new QueryObserver(queryClient, {
queryKey: key,
queryFn: () => 'data',
})
const refetchSpy = jest.spyOn(observer, 'refetch')
const unsubscribe = observer.subscribe(() => undefined)
queryCache.onOnline()
// Should refetch the observer
expect(refetchSpy).toHaveBeenCalledTimes(1)
unsubscribe()
refetchSpy.mockRestore()
})
test('should not add an existing observer', async () => {
const key = queryKey()
await queryClient.prefetchQuery(key, () => 'data')
const query = queryCache.find(key)!
expect(query.getObserversCount()).toEqual(0)
const observer = new QueryObserver(queryClient, {
queryKey: key,
})
expect(query.getObserversCount()).toEqual(0)
query.addObserver(observer)
expect(query.getObserversCount()).toEqual(1)
query.addObserver(observer)
expect(query.getObserversCount()).toEqual(1)
})
test('should not try to remove an observer that does not exist', async () => {
const key = queryKey()
await queryClient.prefetchQuery(key, () => 'data')
const query = queryCache.find(key)!
const observer = new QueryObserver(queryClient, {
queryKey: key,
})
expect(query.getObserversCount()).toEqual(0)
const notifySpy = jest.spyOn(queryCache, 'notify')
expect(() => query.removeObserver(observer)).not.toThrow()
expect(notifySpy).not.toHaveBeenCalled()
notifySpy.mockRestore()
})
test('should not dispatch "invalidate" on invalidate() if already invalidated', async () => {
const key = queryKey()
await queryClient.prefetchQuery(key, () => 'data')
const query = queryCache.find(key)!
query.invalidate()
expect(query.state.isInvalidated).toBeTruthy()
const dispatchOriginal = query['dispatch']
const dispatchSpy = jest.fn()
query['dispatch'] = dispatchSpy
query.invalidate()
expect(query.state.isInvalidated).toBeTruthy()
expect(dispatchSpy).not.toHaveBeenCalled()
query['dispatch'] = dispatchOriginal
})
test('fetch should not dispatch "fetch" if state meta and fetchOptions meta are the same object', async () => {
const key = queryKey()
const queryFn = async () => {
await sleep(10)
return 'data'
}
await queryClient.prefetchQuery(key, queryFn)
const query = queryCache.find(key)!
const meta = { meta1: '1' }
// This first fetch will set the state.meta value
query.fetch(
{
queryKey: key,
queryFn,
},
{
meta,
},
)
// Spy on private dispatch method
const dispatchOriginal = query['dispatch']
const dispatchSpy = jest.fn()
query['dispatch'] = dispatchSpy
// Second fetch in parallel with the same meta
query.fetch(
{
queryKey: key,
queryFn,
},
{
meta,
// cancelRefetch must be set to true to enter in the case to test
// where isFetching is true
cancelRefetch: true,
},
)
// Should not call dispatch with type set to fetch
expect(dispatchSpy).not.toHaveBeenCalledWith({
meta,
type: 'fetch',
})
// Clean-up
await sleep(20)
query['dispatch'] = dispatchOriginal
})
test('fetch should not set the signal in the queryFnContext if AbortController is undefined', async () => {
const key = queryKey()
// Mock the AbortController to be undefined
const AbortControllerOriginal = globalThis['AbortController']
//@ts-expect-error
globalThis['AbortController'] = undefined
let signalTest: any
await queryClient.prefetchQuery(key, ({ signal }) => {
signalTest = signal
return 'data'
})
expect(signalTest).toBeUndefined()
// Clean-up
//@ts-ignore
globalThis['AbortController'] = AbortControllerOriginal
})
test('fetch should throw an error if the queryFn is not defined', async () => {
const key = queryKey()
const observer = new QueryObserver(queryClient, {
queryKey: key,
queryFn: undefined,
retry: false,
})
const unsubscribe = observer.subscribe(() => undefined)
await sleep(10)
expect(mockLogger.error).toHaveBeenCalledWith('Missing queryFn')
unsubscribe()
})
test('fetch should dispatch an error if the queryFn returns undefined', async () => {
const key = queryKey()
const observer = new QueryObserver(queryClient, {
queryKey: key,
queryFn: () => undefined,
retry: false,
})
let observerResult: QueryObserverResult<unknown, unknown> | undefined
const unsubscribe = observer.subscribe((result) => {
observerResult = result
})
await sleep(10)
const error = new Error('Query data cannot be undefined')
expect(observerResult).toMatchObject({
isError: true,
error,
})
expect(mockLogger.error).toHaveBeenCalledWith(error)
unsubscribe()
})
test('fetch should dispatch fetch if is fetching and current promise is undefined', async () => {
const key = queryKey()
const queryFn = async () => {
await sleep(10)
return 'data'
}
await queryClient.prefetchQuery(key, queryFn)
const query = queryCache.find(key)!
query.fetch({
queryKey: key,
queryFn,
})
// Force promise to undefined
// because no use case have been identified
query['promise'] = undefined
// Spy on private dispatch method
const dispatchOriginal = query['dispatch']
const dispatchSpy = jest.fn()
query['dispatch'] = dispatchSpy
query.fetch({
queryKey: key,
queryFn,
})
// Should call dispatch with type set to fetch
expect(dispatchSpy).toHaveBeenCalledWith({
meta: undefined,
type: 'fetch',
})
// Clean-up
await sleep(20)
query['dispatch'] = dispatchOriginal
})
test('constructor should call initialDataUpdatedAt if defined as a function', async () => {
const key = queryKey()
const initialDataUpdatedAtSpy = jest.fn()
await queryClient.prefetchQuery({
queryKey: key,
queryFn: () => 'data',
initialData: 'initial',
initialDataUpdatedAt: initialDataUpdatedAtSpy,
})
expect(initialDataUpdatedAtSpy).toHaveBeenCalled()
})
})