Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

query.test.tsx

885 lines21.7 KB

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})