Open History to see the last commit
1import {
2 sleep,
3 queryKey,
4 mockVisibilityState,
5 mockLogger,
6 createQueryClient,
7} from '../../reactjs/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 () => {
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<void>,
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()
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()
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()
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 () => {
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(key, () => Promise.reject('reject'), {
454 retry: false,
455 })
456 expect(query.state.status).toBe('error')
457β
458 queryClient.prefetchQuery(
459 key,
460 async () => {
461 await sleep(10)
462 return Promise.reject('reject')
463 },
464 { retry: false }
465 )
466 expect(query.state.status).toBe('error')
467β
468 await sleep(100)
469 expect(query.state.status).toBe('error')
470 })
471β
472 test('queries with cacheTime 0 should be removed immediately after unsubscribing', async () => {
473 const key = queryKey()
474 let count = 0
475 const observer = new QueryObserver(queryClient, {
476 queryKey: key,
477 queryFn: () => {
478 count++
479 return 'data'
480 },
481 cacheTime: 0,
482 staleTime: Infinity,
483 })
484 const unsubscribe1 = observer.subscribe(() => undefined)
485 unsubscribe1()
486 await waitFor(() => expect(queryCache.find(key)).toBeUndefined())
487 const unsubscribe2 = observer.subscribe(() => undefined)
488 unsubscribe2()
489β
490 await waitFor(() => expect(queryCache.find(key)).toBeUndefined())
491 expect(count).toBe(1)
492 })
493β
494 test('should be garbage collected when unsubscribed to', async () => {
495 const key = queryKey()
496 const observer = new QueryObserver(queryClient, {
497 queryKey: key,
498 queryFn: async () => 'data',
499 cacheTime: 0,
500 })
501 expect(queryCache.find(key)).toBeDefined()
502 const unsubscribe = observer.subscribe(() => undefined)
503 expect(queryCache.find(key)).toBeDefined()
504 unsubscribe()
505 await waitFor(() => expect(queryCache.find(key)).toBeUndefined())
506 })
507β
508 test('should be garbage collected later when unsubscribed and query is fetching', async () => {
509 const key = queryKey()
510 const observer = new QueryObserver(queryClient, {
511 queryKey: key,
512 queryFn: async () => {
513 await sleep(20)
514 return 'data'
515 },
516 cacheTime: 10,
517 })
518 const unsubscribe = observer.subscribe(() => undefined)
519 await sleep(20)
520 expect(queryCache.find(key)).toBeDefined()
521 observer.refetch()
522 unsubscribe()
523 await sleep(10)
524 // unsubscribe should not remove even though cacheTime has elapsed b/c query is still fetching
525 expect(queryCache.find(key)).toBeDefined()
526 await sleep(10)
527 // should be removed after an additional staleTime wait
528 await waitFor(() => expect(queryCache.find(key)).toBeUndefined())
529 })
530β
531 test('should not be garbage collected unless there are no subscribers', async () => {
532 const key = queryKey()
533 const observer = new QueryObserver(queryClient, {
534 queryKey: key,
535 queryFn: async () => 'data',
536 cacheTime: 0,
537 })
538 expect(queryCache.find(key)).toBeDefined()
539 const unsubscribe = observer.subscribe(() => undefined)
540 await sleep(100)
541 expect(queryCache.find(key)).toBeDefined()
542 unsubscribe()
543 await sleep(100)
544 expect(queryCache.find(key)).toBeUndefined()
545 queryClient.setQueryData(key, 'data')
546 await sleep(100)
547 expect(queryCache.find(key)).toBeDefined()
548 })
549β
550 test('should return proper count of observers', async () => {
551 const key = queryKey()
552 const options = { queryKey: key, queryFn: async () => 'data' }
553 const observer = new QueryObserver(queryClient, options)
554 const observer2 = new QueryObserver(queryClient, options)
555 const observer3 = new QueryObserver(queryClient, options)
556 const query = queryCache.find(key)
557β
558 expect(query?.getObserversCount()).toEqual(0)
559β
560 const unsubscribe1 = observer.subscribe(() => undefined)
561 const unsubscribe2 = observer2.subscribe(() => undefined)
562 const unsubscribe3 = observer3.subscribe(() => undefined)
563 expect(query?.getObserversCount()).toEqual(3)
564β
565 unsubscribe3()
566 expect(query?.getObserversCount()).toEqual(2)
567β
568 unsubscribe2()
569 expect(query?.getObserversCount()).toEqual(1)
570β
571 unsubscribe1()
572 expect(query?.getObserversCount()).toEqual(0)
573 })
574β
575 test('stores meta object in query', async () => {
576 const meta = {
577 it: 'works',
578 }
579β
580 const key = queryKey()
581β
582 await queryClient.prefetchQuery(key, () => 'data', {
583 meta,
584 })
585β
586 const query = queryCache.find(key)!
587β
588 expect(query.meta).toBe(meta)
589 expect(query.options.meta).toBe(meta)
590 })
591β
592 test('updates meta object on change', async () => {
593 const meta = {
594 it: 'works',
595 }
596β
597 const key = queryKey()
598 const queryFn = () => 'data'
599β
600 await queryClient.prefetchQuery(key, queryFn, {
601 meta,
602 })
603β
604 await queryClient.prefetchQuery(key, queryFn, {
605 meta: undefined,
606 })
607β
608 const query = queryCache.find(key)!
609β
610 expect(query.meta).toBeUndefined()
611 expect(query.options.meta).toBeUndefined()
612 })
613β
614 test('provides meta object inside query function', async () => {
615 const meta = {
616 it: 'works',
617 }
618β
619 const queryFn = jest.fn(() => 'data')
620β
621 const key = queryKey()
622β
623 await queryClient.prefetchQuery(key, queryFn, {
624 meta,
625 })
626β
627 expect(queryFn).toBeCalledWith(
628 expect.objectContaining({
629 meta,
630 })
631 )
632 })
633β
634 test('should refetch the observer when online method is called', async () => {
635 const key = queryKey()
636β
637 const observer = new QueryObserver(queryClient, {
638 queryKey: key,
639 queryFn: () => 'data',
640 })
641β
642 const refetchSpy = jest.spyOn(observer, 'refetch')
643 const unsubscribe = observer.subscribe(() => undefined)
644 queryCache.onOnline()
645β
646 // Should refetch the observer
647 expect(refetchSpy).toHaveBeenCalledTimes(1)
648β
649 unsubscribe()
650 refetchSpy.mockRestore()
651 })
652β
653 test('should not add an existing observer', async () => {
654 const key = queryKey()
655β
656 await queryClient.prefetchQuery(key, () => 'data')
657 const query = queryCache.find(key)!
658 expect(query.getObserversCount()).toEqual(0)
659β
660 const observer = new QueryObserver(queryClient, {
661 queryKey: key,
662 })
663 expect(query.getObserversCount()).toEqual(0)
664β
665 query.addObserver(observer)
666 expect(query.getObserversCount()).toEqual(1)
667β
668 query.addObserver(observer)
669 expect(query.getObserversCount()).toEqual(1)
670 })
671β
672 test('should not try to remove an observer that does not exist', async () => {
673 const key = queryKey()
674β
675 await queryClient.prefetchQuery(key, () => 'data')
676 const query = queryCache.find(key)!
677 const observer = new QueryObserver(queryClient, {
678 queryKey: key,
679 })
680 expect(query.getObserversCount()).toEqual(0)
681β
682 const notifySpy = jest.spyOn(queryCache, 'notify')
683 expect(() => query.removeObserver(observer)).not.toThrow()
684 expect(notifySpy).not.toHaveBeenCalled()
685β
686 notifySpy.mockRestore()
687 })
688β
689 test('should not dispatch "invalidate" on invalidate() if already invalidated', async () => {
690 const key = queryKey()
691β
692 await queryClient.prefetchQuery(key, () => 'data')
693 const query = queryCache.find(key)!
694β
695 query.invalidate()
696 expect(query.state.isInvalidated).toBeTruthy()
697β
698 const dispatchOriginal = query['dispatch']
699 const dispatchSpy = jest.fn()
700 query['dispatch'] = dispatchSpy
701β
702 query.invalidate()
703β
704 expect(query.state.isInvalidated).toBeTruthy()
705 expect(dispatchSpy).not.toHaveBeenCalled()
706β
707 query['dispatch'] = dispatchOriginal
708 })
709β
710 test('fetch should not dispatch "fetch" if state meta and fetchOptions meta are the same object', async () => {
711 const key = queryKey()
712β
713 const queryFn = async () => {
714 await sleep(10)
715 return 'data'
716 }
717β
718 await queryClient.prefetchQuery(key, queryFn)
719 const query = queryCache.find(key)!
720β
721 const meta = { meta1: '1' }
722β
723 // This first fetch will set the state.meta value
724 query.fetch(
725 {
726 queryKey: key,
727 queryFn,
728 },
729 {
730 meta,
731 }
732 )
733β
734 // Spy on private dispatch method
735 const dispatchOriginal = query['dispatch']
736 const dispatchSpy = jest.fn()
737 query['dispatch'] = dispatchSpy
738β
739 // Second fetch in parallel with the same meta
740 query.fetch(
741 {
742 queryKey: key,
743 queryFn,
744 },
745 {
746 meta,
747 // cancelRefetch must be set to true to enter in the case to test
748 // where isFetching is true
749 cancelRefetch: true,
750 }
751 )
752β
753 // Should not call dispatch with type set to fetch
754 expect(dispatchSpy).not.toHaveBeenCalledWith({
755 meta,
756 type: 'fetch',
757 })
758β
759 // Clean-up
760 await sleep(20)
761 query['dispatch'] = dispatchOriginal
762 })
763β
764 test('fetch should not set the signal in the queryFnContext if AbortController is undefined', async () => {
765 const key = queryKey()
766β
767 // Mock the AbortController to be undefined
768 const AbortControllerOriginal = globalThis['AbortController']
769 //@ts-expect-error
770 globalThis['AbortController'] = undefined
771β
772 let signalTest: any
773 await queryClient.prefetchQuery(key, ({ signal }) => {
774 signalTest = signal
775 return 'data'
776 })
777β
778 expect(signalTest).toBeUndefined()
779β
780 // Clean-up
781 //@ts-ignore
782 globalThis['AbortController'] = AbortControllerOriginal
783 })
784β
785 test('fetch should throw an error if the queryFn is not defined', async () => {
786 const key = queryKey()
787β
788 const observer = new QueryObserver(queryClient, {
789 queryKey: key,
790 queryFn: undefined,
791 retry: false,
792 })
793β
794 const unsubscribe = observer.subscribe(() => undefined)
795 await sleep(10)
796 expect(mockLogger.error).toHaveBeenCalledWith('Missing queryFn')
797β
798 unsubscribe()
799 })
800β
801 test('fetch should dispatch an error if the queryFn returns undefined', async () => {
802 const key = queryKey()
803β
804 const observer = new QueryObserver(queryClient, {
805 queryKey: key,
806 // @ts-expect-error (queryFn must not return undefined)
807 queryFn: () => undefined,
808 retry: false,
809 })
810β
811 let observerResult: QueryObserverResult<unknown, unknown> | undefined
812β
813 const unsubscribe = observer.subscribe(result => {
814 observerResult = result
815 })
816β
817 await sleep(10)
818β
819 const error = new Error('Query data cannot be undefined')
820β
821 expect(observerResult).toMatchObject({
822 isError: true,
823 error,
824 })
825β
826 expect(mockLogger.error).toHaveBeenCalledWith(error)
827 unsubscribe()
828 })
829β
830 test('fetch should dispatch fetch if is fetching and current promise is undefined', async () => {
831 const key = queryKey()
832β
833 const queryFn = async () => {
834 await sleep(10)
835 return 'data'
836 }
837β
838 await queryClient.prefetchQuery(key, queryFn)
839 const query = queryCache.find(key)!
840β
841 query.fetch({
842 queryKey: key,
843 queryFn,
844 })
845β
846 // Force promise to undefined
847 // because no use case have been identified
848 query['promise'] = undefined
849β
850 // Spy on private dispatch method
851 const dispatchOriginal = query['dispatch']
852 const dispatchSpy = jest.fn()
853 query['dispatch'] = dispatchSpy
854β
855 query.fetch({
856 queryKey: key,
857 queryFn,
858 })
859β
860 // Should call dispatch with type set to fetch
861 expect(dispatchSpy).toHaveBeenCalledWith({
862 meta: undefined,
863 type: 'fetch',
864 })
865β
866 // Clean-up
867 await sleep(20)
868 query['dispatch'] = dispatchOriginal
869 })
870β
871 test('constructor should call initialDataUpdatedAt if defined as a function', async () => {
872 const key = queryKey()
873β
874 const initialDataUpdatedAtSpy = jest.fn()
875β
876 await queryClient.prefetchQuery({
877 queryKey: key,
878 queryFn: () => 'data',
879 initialData: 'initial',
880 initialDataUpdatedAt: initialDataUpdatedAtSpy,
881 })
882β
883 expect(initialDataUpdatedAtSpy).toHaveBeenCalled()
884 })
885})