Open History to see the last commit
1import {
2 sleep,
3 queryKey,
4 mockVisibilityState,
5 mockLogger,
6 createQueryClient,
7} from '../../../../tests/utils'
8import {
9 QueryCache,
10 QueryClient,
11 QueryObserver,
12 isCancelledError,
13 isError,
14 onlineManager,
15 QueryFunctionContext,
16 QueryObserverResult,
17} from '..'
18import { waitFor } from '@testing-library/react'
19β
20describe('query', () => {
21 let queryClient: QueryClient
22 let queryCache: QueryCache
23β
24 beforeEach(() => {
25 queryClient = createQueryClient()
26 queryCache = queryClient.getQueryCache()
27 queryClient.mount()
28 })
29β
30 afterEach(() => {
31 queryClient.clear()
32 })
33β
34 test('should use the longest cache time it has seen', async () => {
35 const key = queryKey()
36 await queryClient.prefetchQuery(key, () => 'data', {
37 cacheTime: 100,
38 })
39 await queryClient.prefetchQuery(key, () => 'data', {
40 cacheTime: 200,
41 })
42 await queryClient.prefetchQuery(key, () => 'data', {
43 cacheTime: 10,
44 })
45 const query = queryCache.find(key)!
46 expect(query.cacheTime).toBe(200)
47 })
48β
49 it('should continue retry after focus regain and resolve all promises', async () => {
50 const key = queryKey()
51β
52 // make page unfocused
53 const visibilityMock = mockVisibilityState('hidden')
54β
55 let count = 0
56 let result
57β
58 const promise = queryClient.fetchQuery(
59 key,
60 async () => {
61 count++
62β
63 if (count === 3) {
64 return `data${count}`
65 }
66β
67 throw new Error(`error${count}`)
68 },
69 {
70 retry: 3,
71 retryDelay: 1,
72 },
73 )
74β
75 promise.then((data) => {
76 result = data
77 })
78β
79 // Check if we do not have a result
80 expect(result).toBeUndefined()
81β
82 // Check if the query is really paused
83 await sleep(50)
84 expect(result).toBeUndefined()
85β
86 // Reset visibilityState to original value
87 visibilityMock.mockRestore()
88 window.dispatchEvent(new FocusEvent('focus'))
89β
90 // There should not be a result yet
91 expect(result).toBeUndefined()
92β
93 // By now we should have a value
94 await sleep(50)
95 expect(result).toBe('data3')
96 })
97β
98 it('should continue retry after reconnect and resolve all promises', async () => {
99 const key = queryKey()
100β
101 onlineManager.setOnline(false)
102β
103 let count = 0
104 let result
105β
106 const promise = queryClient.fetchQuery(
107 key,
108 async () => {
109 count++
110β
111 if (count === 3) {
112 return `data${count}`
113 }
114β
115 throw new Error(`error${count}`)
116 },
117 {
118 retry: 3,
119 retryDelay: 1,
120 },
121 )
122β
123 promise.then((data) => {
124 result = data
125 })
126β
127 // Check if we do not have a result
128 expect(result).toBeUndefined()
129β
130 // Check if the query is really paused
131 await sleep(50)
132 expect(result).toBeUndefined()
133β
134 // Reset navigator to original value
135 onlineManager.setOnline(true)
136β
137 // There should not be a result yet
138 expect(result).toBeUndefined()
139β
140 // By now we should have a value
141 await sleep(50)
142 expect(result).toBe('data3')
143 })
144β
145 it('should throw a CancelledError when a paused query is cancelled', async () => {
146 const key = queryKey()
147β
148 // make page unfocused
149 const visibilityMock = mockVisibilityState('hidden')
150β
151 let count = 0
152 let result
153β
154 const promise = queryClient.fetchQuery(
155 key,
156 async (): Promise<unknown> => {
157 count++
158 throw new Error(`error${count}`)
159 },
160 {
161 retry: 3,
162 retryDelay: 1,
163 },
164 )
165β
166 promise.catch((data) => {
167 result = data
168 })
169β
170 const query = queryCache.find(key)!
171β
172 // Check if the query is really paused
173 await sleep(50)
174 expect(result).toBeUndefined()
175β
176 // Cancel query
177 query.cancel()
178β
179 // Check if the error is set to the cancelled error
180 await sleep(0)
181 expect(isCancelledError(result)).toBe(true)
182β
183 // Reset visibilityState to original value
184 visibilityMock.mockRestore()
185 window.dispatchEvent(new FocusEvent('focus'))
186 })
187β
188 test('should provide context to queryFn', async () => {
189 const key = queryKey()
190β
191 const queryFn = jest
192 .fn<
193 Promise<'data'>,
194 [QueryFunctionContext<ReturnType<typeof queryKey>>]
195 >()
196 .mockResolvedValue('data')
197β
198 queryClient.prefetchQuery(key, queryFn)
199β
200 await sleep(10)
201β
202 expect(queryFn).toHaveBeenCalledTimes(1)
203 const args = queryFn.mock.calls[0]![0]
204 expect(args).toBeDefined()
205 expect(args.pageParam).toBeUndefined()
206 expect(args.queryKey).toEqual(key)
207 if (typeof AbortSignal === 'function') {
208 expect(args.signal).toBeInstanceOf(AbortSignal)
209 } else {
210 expect(args.signal).toBeUndefined()
211 }
212 })
213β
214 test('should continue if cancellation is not supported and signal is not consumed', async () => {
215 const key = queryKey()
216β
217 queryClient.prefetchQuery(key, async () => {
218 await sleep(100)
219 return 'data'
220 })
221β
222 await sleep(10)
223β
224 // Subscribe and unsubscribe to simulate cancellation because the last observer unsubscribed
225 const observer = new QueryObserver(queryClient, {
226 queryKey: key,
227 enabled: false,
228 })
229 const unsubscribe = observer.subscribe(() => undefined)
230 unsubscribe()
231β
232 await sleep(100)
233β
234 const query = queryCache.find(key)!
235β
236 expect(query.state).toMatchObject({
237 data: 'data',
238 status: 'success',
239 dataUpdateCount: 1,
240 })
241 })
242β
243 test('should not continue when last observer unsubscribed if the signal was consumed', async () => {
244 const key = queryKey()
245β
246 queryClient.prefetchQuery(key, async ({ signal }) => {
247 await sleep(100)
248 return signal?.aborted ? 'aborted' : 'data'
249 })
250β
251 await sleep(10)
252β
253 // Subscribe and unsubscribe to simulate cancellation because the last observer unsubscribed
254 const observer = new QueryObserver(queryClient, {
255 queryKey: key,
256 enabled: false,
257 })
258 const unsubscribe = observer.subscribe(() => undefined)
259 unsubscribe()
260β
261 await sleep(100)
262β
263 const query = queryCache.find(key)!
264β
265 if (typeof AbortSignal === 'function') {
266 expect(query.state).toMatchObject({
267 data: undefined,
268 status: 'loading',
269 fetchStatus: 'idle',
270 })
271 } else {
272 expect(query.state).toMatchObject({
273 data: 'data',
274 status: 'success',
275 fetchStatus: 'idle',
276 dataUpdateCount: 1,
277 })
278 }
279 })
280β
281 test('should provide an AbortSignal to the queryFn that provides info about the cancellation state', async () => {
282 const key = queryKey()
283β
284 const queryFn = jest.fn<
285 Promise<unknown>,
286 [QueryFunctionContext<ReturnType<typeof queryKey>>]
287 >()
288 const onAbort = jest.fn()
289 const abortListener = jest.fn()
290 let error
291β
292 queryFn.mockImplementation(async ({ signal }) => {
293 if (signal) {
294 signal.onabort = onAbort
295 signal.addEventListener('abort', abortListener)
296 }
297 await sleep(10)
298 if (signal) {
299 signal.onabort = null
300 signal.removeEventListener('abort', abortListener)
301 }
302 throw new Error()
303 })
304β
305 const promise = queryClient.fetchQuery(key, queryFn, {
306 retry: 3,
307 retryDelay: 10,
308 })
309β
310 promise.catch((e) => {
311 error = e
312 })
313β
314 const query = queryCache.find(key)!
315β
316 expect(queryFn).toHaveBeenCalledTimes(1)
317β
318 let signal = queryFn.mock.calls[0]![0].signal
319β
320 if (typeof AbortSignal === 'function') {
321 signal = queryFn.mock.calls[0]![0].signal
322 expect(signal?.aborted).toBe(false)
323 }
324 expect(onAbort).not.toHaveBeenCalled()
325 expect(abortListener).not.toHaveBeenCalled()
326β
327 query.cancel()
328β
329 await sleep(100)
330β
331 if (typeof AbortSignal === 'function') {
332 expect(signal?.aborted).toBe(true)
333 expect(onAbort).toHaveBeenCalledTimes(1)
334 expect(abortListener).toHaveBeenCalledTimes(1)
335 }
336 expect(isCancelledError(error)).toBe(true)
337 })
338β
339 test('should not continue if explicitly cancelled', async () => {
340 const key = queryKey()
341β
342 const queryFn = jest.fn<unknown, unknown[]>()
343β
344 queryFn.mockImplementation(async () => {
345 await sleep(10)
346 throw new Error()
347 })
348β
349 let error
350β
351 const promise = queryClient.fetchQuery(key, queryFn, {
352 retry: 3,
353 retryDelay: 10,
354 })
355β
356 promise.catch((e) => {
357 error = e
358 })
359β
360 const query = queryCache.find(key)!
361 query.cancel()
362β
363 await sleep(100)
364β
365 expect(queryFn).toHaveBeenCalledTimes(1)
366 expect(isCancelledError(error)).toBe(true)
367 })
368β
369 test('should not error if reset while loading', async () => {
370 const key = queryKey()
371β
372 const queryFn = jest.fn<unknown, unknown[]>()
373β
374 queryFn.mockImplementation(async () => {
375 await sleep(10)
376 throw new Error()
377 })
378β
379 queryClient.fetchQuery(key, queryFn, {
380 retry: 3,
381 retryDelay: 10,
382 })
383β
384 // Ensure the query is loading
385 const query = queryCache.find(key)!
386 expect(query.state.status).toBe('loading')
387β
388 // Reset the query while it is loading
389 query.reset()
390β
391 await sleep(100)
392β
393 // The query should
394 expect(queryFn).toHaveBeenCalledTimes(1) // have been called,
395 expect(query.state.error).toBe(null) // not have an error, and
396 expect(query.state.fetchStatus).toBe('idle') // not be loading any longer
397 })
398β
399 test('should be able to refetch a cancelled query', async () => {
400 const key = queryKey()
401β
402 const queryFn = jest.fn<unknown, unknown[]>()
403β
404 queryFn.mockImplementation(async () => {
405 await sleep(50)
406 return 'data'
407 })
408β
409 queryClient.prefetchQuery(key, queryFn)
410 const query = queryCache.find(key)!
411 await sleep(10)
412 query.cancel()
413 await sleep(100)
414β
415 expect(queryFn).toHaveBeenCalledTimes(1)
416 expect(isCancelledError(query.state.error)).toBe(true)
417 const result = await query.fetch()
418 expect(result).toBe('data')
419 expect(query.state.error).toBe(null)
420 expect(queryFn).toHaveBeenCalledTimes(2)
421 })
422β
423 test('cancelling a resolved query should not have any effect', async () => {
424 const key = queryKey()
425 await queryClient.prefetchQuery(key, async () => 'data')
426 const query = queryCache.find(key)!
427 query.cancel()
428 await sleep(10)
429 expect(query.state.data).toBe('data')
430 })
431β
432 test('cancelling a rejected query should not have any effect', async () => {
433 const key = queryKey()
434β
435 await queryClient.prefetchQuery(key, async (): Promise<unknown> => {
436 throw new Error('error')
437 })
438 const query = queryCache.find(key)!
439 query.cancel()
440 await sleep(10)
441β
442 expect(isError(query.state.error)).toBe(true)
443 expect(isCancelledError(query.state.error)).toBe(false)
444 })
445β
446 test('the previous query status should be kept when refetching', async () => {
447 const key = queryKey()
448β
449 await queryClient.prefetchQuery(key, () => 'data')
450 const query = queryCache.find(key)!
451 expect(query.state.status).toBe('success')
452β
453 await queryClient.prefetchQuery(
454 key,
455 () => Promise.reject<string>('reject'),
456 {
457 retry: false,
458 },
459 )
460 expect(query.state.status).toBe('error')
461β
462 queryClient.prefetchQuery(
463 key,
464 async () => {
465 await sleep(10)
466 return Promise.reject<unknown>('reject')
467 },
468 { retry: false },
469 )
470 expect(query.state.status).toBe('error')
471β
472 await sleep(100)
473 expect(query.state.status).toBe('error')
474 })
475β
476 test('queries with cacheTime 0 should be removed immediately after unsubscribing', async () => {
477 const key = queryKey()
478 let count = 0
479 const observer = new QueryObserver(queryClient, {
480 queryKey: key,
481 queryFn: () => {
482 count++
483 return 'data'
484 },
485 cacheTime: 0,
486 staleTime: Infinity,
487 })
488 const unsubscribe1 = observer.subscribe(() => undefined)
489 unsubscribe1()
490 await waitFor(() => expect(queryCache.find(key)).toBeUndefined())
491 const unsubscribe2 = observer.subscribe(() => undefined)
492 unsubscribe2()
493β
494 await waitFor(() => expect(queryCache.find(key)).toBeUndefined())
495 expect(count).toBe(1)
496 })
497β
498 test('should be garbage collected when unsubscribed to', async () => {
499 const key = queryKey()
500 const observer = new QueryObserver(queryClient, {
501 queryKey: key,
502 queryFn: async () => 'data',
503 cacheTime: 0,
504 })
505 expect(queryCache.find(key)).toBeDefined()
506 const unsubscribe = observer.subscribe(() => undefined)
507 expect(queryCache.find(key)).toBeDefined()
508 unsubscribe()
509 await waitFor(() => expect(queryCache.find(key)).toBeUndefined())
510 })
511β
512 test('should be garbage collected later when unsubscribed and query is fetching', async () => {
513 const key = queryKey()
514 const observer = new QueryObserver(queryClient, {
515 queryKey: key,
516 queryFn: async () => {
517 await sleep(20)
518 return 'data'
519 },
520 cacheTime: 10,
521 })
522 const unsubscribe = observer.subscribe(() => undefined)
523 await sleep(20)
524 expect(queryCache.find(key)).toBeDefined()
525 observer.refetch()
526 unsubscribe()
527 await sleep(10)
528 // unsubscribe should not remove even though cacheTime has elapsed b/c query is still fetching
529 expect(queryCache.find(key)).toBeDefined()
530 await sleep(10)
531 // should be removed after an additional staleTime wait
532 await waitFor(() => expect(queryCache.find(key)).toBeUndefined())
533 })
534β
535 test('should not be garbage collected unless there are no subscribers', async () => {
536 const key = queryKey()
537 const observer = new QueryObserver(queryClient, {
538 queryKey: key,
539 queryFn: async () => 'data',
540 cacheTime: 0,
541 })
542 expect(queryCache.find(key)).toBeDefined()
543 const unsubscribe = observer.subscribe(() => undefined)
544 await sleep(100)
545 expect(queryCache.find(key)).toBeDefined()
546 unsubscribe()
547 await sleep(100)
548 expect(queryCache.find(key)).toBeUndefined()
549 queryClient.setQueryData(key, 'data')
550 await sleep(100)
551 expect(queryCache.find(key)).toBeDefined()
552 })
553β
554 test('should return proper count of observers', async () => {
555 const key = queryKey()
556 const options = { queryKey: key, queryFn: async () => 'data' }
557 const observer = new QueryObserver(queryClient, options)
558 const observer2 = new QueryObserver(queryClient, options)
559 const observer3 = new QueryObserver(queryClient, options)
560 const query = queryCache.find(key)
561β
562 expect(query?.getObserversCount()).toEqual(0)
563β
564 const unsubscribe1 = observer.subscribe(() => undefined)
565 const unsubscribe2 = observer2.subscribe(() => undefined)
566 const unsubscribe3 = observer3.subscribe(() => undefined)
567 expect(query?.getObserversCount()).toEqual(3)
568β
569 unsubscribe3()
570 expect(query?.getObserversCount()).toEqual(2)
571β
572 unsubscribe2()
573 expect(query?.getObserversCount()).toEqual(1)
574β
575 unsubscribe1()
576 expect(query?.getObserversCount()).toEqual(0)
577 })
578β
579 test('stores meta object in query', async () => {
580 const meta = {
581 it: 'works',
582 }
583β
584 const key = queryKey()
585β
586 await queryClient.prefetchQuery(key, () => 'data', {
587 meta,
588 })
589β
590 const query = queryCache.find(key)!
591β
592 expect(query.meta).toBe(meta)
593 expect(query.options.meta).toBe(meta)
594 })
595β
596 test('updates meta object on change', async () => {
597 const meta = {
598 it: 'works',
599 }
600β
601 const key = queryKey()
602 const queryFn = () => 'data'
603β
604 await queryClient.prefetchQuery(key, queryFn, {
605 meta,
606 })
607β
608 await queryClient.prefetchQuery(key, queryFn, {
609 meta: undefined,
610 })
611β
612 const query = queryCache.find(key)!
613β
614 expect(query.meta).toBeUndefined()
615 expect(query.options.meta).toBeUndefined()
616 })
617β
618 test('provides meta object inside query function', async () => {
619 const meta = {
620 it: 'works',
621 }
622β
623 const queryFn = jest.fn(() => 'data')
624β
625 const key = queryKey()
626β
627 await queryClient.prefetchQuery(key, queryFn, {
628 meta,
629 })
630β
631 expect(queryFn).toBeCalledWith(
632 expect.objectContaining({
633 meta,
634 }),
635 )
636 })
637β
638 test('should refetch the observer when online method is called', async () => {
639 const key = queryKey()
640β
641 const observer = new QueryObserver(queryClient, {
642 queryKey: key,
643 queryFn: () => 'data',
644 })
645β
646 const refetchSpy = jest.spyOn(observer, 'refetch')
647 const unsubscribe = observer.subscribe(() => undefined)
648 queryCache.onOnline()
649β
650 // Should refetch the observer
651 expect(refetchSpy).toHaveBeenCalledTimes(1)
652β
653 unsubscribe()
654 refetchSpy.mockRestore()
655 })
656β
657 test('should not add an existing observer', async () => {
658 const key = queryKey()
659β
660 await queryClient.prefetchQuery(key, () => 'data')
661 const query = queryCache.find(key)!
662 expect(query.getObserversCount()).toEqual(0)
663β
664 const observer = new QueryObserver(queryClient, {
665 queryKey: key,
666 })
667 expect(query.getObserversCount()).toEqual(0)
668β
669 query.addObserver(observer)
670 expect(query.getObserversCount()).toEqual(1)
671β
672 query.addObserver(observer)
673 expect(query.getObserversCount()).toEqual(1)
674 })
675β
676 test('should not try to remove an observer that does not exist', async () => {
677 const key = queryKey()
678β
679 await queryClient.prefetchQuery(key, () => 'data')
680 const query = queryCache.find(key)!
681 const observer = new QueryObserver(queryClient, {
682 queryKey: key,
683 })
684 expect(query.getObserversCount()).toEqual(0)
685β
686 const notifySpy = jest.spyOn(queryCache, 'notify')
687 expect(() => query.removeObserver(observer)).not.toThrow()
688 expect(notifySpy).not.toHaveBeenCalled()
689β
690 notifySpy.mockRestore()
691 })
692β
693 test('should not dispatch "invalidate" on invalidate() if already invalidated', async () => {
694 const key = queryKey()
695β
696 await queryClient.prefetchQuery(key, () => 'data')
697 const query = queryCache.find(key)!
698β
699 query.invalidate()
700 expect(query.state.isInvalidated).toBeTruthy()
701β
702 const dispatchOriginal = query['dispatch']
703 const dispatchSpy = jest.fn()
704 query['dispatch'] = dispatchSpy
705β
706 query.invalidate()
707β
708 expect(query.state.isInvalidated).toBeTruthy()
709 expect(dispatchSpy).not.toHaveBeenCalled()
710β
711 query['dispatch'] = dispatchOriginal
712 })
713β
714 test('fetch should not dispatch "fetch" if state meta and fetchOptions meta are the same object', async () => {
715 const key = queryKey()
716β
717 const queryFn = async () => {
718 await sleep(10)
719 return 'data'
720 }
721β
722 await queryClient.prefetchQuery(key, queryFn)
723 const query = queryCache.find(key)!
724β
725 const meta = { meta1: '1' }
726β
727 // This first fetch will set the state.meta value
728 query.fetch(
729 {
730 queryKey: key,
731 queryFn,
732 },
733 {
734 meta,
735 },
736 )
737β
738 // Spy on private dispatch method
739 const dispatchOriginal = query['dispatch']
740 const dispatchSpy = jest.fn()
741 query['dispatch'] = dispatchSpy
742β
743 // Second fetch in parallel with the same meta
744 query.fetch(
745 {
746 queryKey: key,
747 queryFn,
748 },
749 {
750 meta,
751 // cancelRefetch must be set to true to enter in the case to test
752 // where isFetching is true
753 cancelRefetch: true,
754 },
755 )
756β
757 // Should not call dispatch with type set to fetch
758 expect(dispatchSpy).not.toHaveBeenCalledWith({
759 meta,
760 type: 'fetch',
761 })
762β
763 // Clean-up
764 await sleep(20)
765 query['dispatch'] = dispatchOriginal
766 })
767β
768 test('fetch should not set the signal in the queryFnContext if AbortController is undefined', async () => {
769 const key = queryKey()
770β
771 // Mock the AbortController to be undefined
772 const AbortControllerOriginal = globalThis['AbortController']
773 //@ts-expect-error
774 globalThis['AbortController'] = undefined
775β
776 let signalTest: any
777 await queryClient.prefetchQuery(key, ({ signal }) => {
778 signalTest = signal
779 return 'data'
780 })
781β
782 expect(signalTest).toBeUndefined()
783β
784 // Clean-up
785 //@ts-ignore
786 globalThis['AbortController'] = AbortControllerOriginal
787 })
788β
789 test('fetch should throw an error if the queryFn is not defined', async () => {
790 const key = queryKey()
791β
792 const observer = new QueryObserver(queryClient, {
793 queryKey: key,
794 queryFn: undefined,
795 retry: false,
796 })
797β
798 const unsubscribe = observer.subscribe(() => undefined)
799 await sleep(10)
800 expect(mockLogger.error).toHaveBeenCalledWith('Missing queryFn')
801β
802 unsubscribe()
803 })
804β
805 test('fetch should dispatch an error if the queryFn returns undefined', async () => {
806 const key = queryKey()
807β
808 const observer = new QueryObserver(queryClient, {
809 queryKey: key,
810 queryFn: () => undefined,
811 retry: false,
812 })
813β
814 let observerResult: QueryObserverResult<unknown, unknown> | undefined
815β
816 const unsubscribe = observer.subscribe((result) => {
817 observerResult = result
818 })
819β
820 await sleep(10)
821β
822 const error = new Error('Query data cannot be undefined')
823β
824 expect(observerResult).toMatchObject({
825 isError: true,
826 error,
827 })
828β
829 expect(mockLogger.error).toHaveBeenCalledWith(error)
830 unsubscribe()
831 })
832β
833 test('fetch should dispatch fetch if is fetching and current promise is undefined', async () => {
834 const key = queryKey()
835β
836 const queryFn = async () => {
837 await sleep(10)
838 return 'data'
839 }
840β
841 await queryClient.prefetchQuery(key, queryFn)
842 const query = queryCache.find(key)!
843β
844 query.fetch({
845 queryKey: key,
846 queryFn,
847 })
848β
849 // Force promise to undefined
850 // because no use case have been identified
851 query['promise'] = undefined
852β
853 // Spy on private dispatch method
854 const dispatchOriginal = query['dispatch']
855 const dispatchSpy = jest.fn()
856 query['dispatch'] = dispatchSpy
857β
858 query.fetch({
859 queryKey: key,
860 queryFn,
861 })
862β
863 // Should call dispatch with type set to fetch
864 expect(dispatchSpy).toHaveBeenCalledWith({
865 meta: undefined,
866 type: 'fetch',
867 })
868β
869 // Clean-up
870 await sleep(20)
871 query['dispatch'] = dispatchOriginal
872 })
873β
874 test('constructor should call initialDataUpdatedAt if defined as a function', async () => {
875 const key = queryKey()
876β
877 const initialDataUpdatedAtSpy = jest.fn()
878β
879 await queryClient.prefetchQuery({
880 queryKey: key,
881 queryFn: () => 'data',
882 initialData: 'initial',
883 initialDataUpdatedAt: initialDataUpdatedAtSpy,
884 })
885β
886 expect(initialDataUpdatedAtSpy).toHaveBeenCalled()
887 })
888})