Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2import {
3 mockVisibilityState,
4 queryKey,
5 sleep,
6} from '@tanstack/query-test-utils'
7import {
8 CancelledError,
9 Query,
10 QueryClient,
11 QueryObserver,
12 dehydrate,
13 hydrate,
14} from '..'
15import { hashQueryKeyByOptions } from '../utils'
16import { mockOnlineManagerIsOnline, setIsServer } from './utils'
17import type {
18 QueryCache,
19 QueryFunctionContext,
20 QueryKey,
21 QueryObserverResult,
22} from '..'
23β
24describe('query', () => {
25 let queryClient: QueryClient
26 let queryCache: QueryCache
27β
28 beforeEach(() => {
29 vi.useFakeTimers()
30 queryClient = new QueryClient()
31 queryCache = queryClient.getQueryCache()
32 queryClient.mount()
33 })
34β
35 afterEach(() => {
36 queryClient.clear()
37 vi.useRealTimers()
38 })
39β
40 it('should use the longest garbage collection time it has seen', async () => {
41 const key = queryKey()
42 await queryClient.prefetchQuery({
43 queryKey: key,
44 queryFn: () => 'data',
45 gcTime: 100,
46 })
47 await queryClient.prefetchQuery({
48 queryKey: key,
49 queryFn: () => 'data',
50 gcTime: 200,
51 })
52 await queryClient.prefetchQuery({
53 queryKey: key,
54 queryFn: () => 'data',
55 gcTime: 10,
56 })
57 const query = queryCache.find({ queryKey: key })!
58 expect(query.gcTime).toBe(200)
59 })
60β
61 it('should continue retry after focus regain and resolve all promises', async () => {
62 const key = queryKey()
63β
64 // make page unfocused
65 const visibilityMock = mockVisibilityState('hidden')
66β
67 let count = 0
68 let result
69β
70 const promise = queryClient.fetchQuery({
71 queryKey: key,
72 queryFn: () => {
73 count++
74β
75 if (count === 3) {
76 return `data${count}`
77 }
78β
79 throw new Error(`error${count}`)
80 },
81 retry: 3,
82 retryDelay: 1,
83 })
84β
85 promise.then((data) => {
86 result = data
87 })
88β
89 // Check if we do not have a result
90 expect(result).toBeUndefined()
91β
92 // Check if the query is really paused
93 await vi.advanceTimersByTimeAsync(50)
94 expect(result).toBeUndefined()
95β
96 // Reset visibilityState to original value
97 visibilityMock.mockRestore()
98 window.dispatchEvent(new Event('visibilitychange'))
99β
100 // There should not be a result yet
101 expect(result).toBeUndefined()
102β
103 // By now we should have a value
104 await vi.advanceTimersByTimeAsync(50)
105 expect(result).toBe('data3')
106 })
107β
108 it('should continue retry after reconnect and resolve all promises', async () => {
109 const key = queryKey()
110β
111 const onlineMock = mockOnlineManagerIsOnline(false)
112β
113 let count = 0
114 let result
115β
116 const promise = queryClient.fetchQuery({
117 queryKey: key,
118 queryFn: () => {
119 count++
120β
121 if (count === 3) {
122 return `data${count}`
123 }
124β
125 throw new Error(`error${count}`)
126 },
127 retry: 3,
128 retryDelay: 1,
129 })
130β
131 promise.then((data) => {
132 result = data
133 })
134β
135 // Check if we do not have a result
136 expect(result).toBeUndefined()
137β
138 // Check if the query is really paused
139 await vi.advanceTimersByTimeAsync(1)
140 expect(result).toBeUndefined()
141β
142 // Reset navigator to original value
143 onlineMock.mockReturnValue(true)
144 // trigger online event
145 queryClient.getQueryCache().onOnline()
146β
147 // There should not be a result yet
148 expect(result).toBeUndefined()
149β
150 // Promise should eventually be resolved
151 await vi.advanceTimersByTimeAsync(2)
152 expect(result).toBe('data3')
153 onlineMock.mockRestore()
154 })
155β
156 it('should throw a CancelledError when a paused query is cancelled', async () => {
157 const key = queryKey()
158β
159 // make page unfocused
160 const visibilityMock = mockVisibilityState('hidden')
161 let count = 0
162β
163 const promise = queryClient.fetchQuery({
164 queryKey: key,
165 queryFn: (): Promise<unknown> => {
166 count++
167 throw new Error(`error${count}`)
168 },
169 retry: 3,
170 retryDelay: 1,
171 })
172β
173 const query = queryCache.find({ queryKey: key })!
174β
175 // Check if the query is really paused
176 await vi.advanceTimersByTimeAsync(50)
177 expect(query.state.fetchStatus).toBe('paused')
178β
179 // Cancel query
180 query.cancel()
181β
182 // Check if the error is set to the cancelled error
183 try {
184 await expect(promise).rejects.toBeInstanceOf(CancelledError)
185 } finally {
186 // Reset visibilityState to original value
187 visibilityMock.mockRestore()
188 }
189 })
190β
191 it('should cancel a paused initial fetch when the last observer unsubscribes', async () => {
192 const key = queryKey()
193 const onlineMock = mockOnlineManagerIsOnline(false)
194 let count = 0
195β
196 const observer = new QueryObserver(queryClient, {
197 queryKey: key,
198 queryFn: async ({ signal: _signal }) => {
199 count++
200 await sleep(10)
201 return `data${count}`
202 },
203 })
204β
205 const unsubscribe = observer.subscribe(() => undefined)
206 const query = queryCache.find({ queryKey: key })!
207β
208 expect(query.state).toMatchObject({
209 fetchStatus: 'paused',
210 status: 'pending',
211 })
212β
213 unsubscribe()
214β
215 expect(query.state).toMatchObject({
216 fetchStatus: 'idle',
217 status: 'pending',
218 })
219β
220 onlineMock.mockReturnValue(true)
221 queryClient.getQueryCache().onOnline()
222β
223 await vi.advanceTimersByTimeAsync(11)
224β
225 expect(query.state).toMatchObject({
226 fetchStatus: 'idle',
227 status: 'pending',
228 })
229 expect(count).toBe(0)
230β
231 onlineMock.mockRestore()
232 })
233β
234 it('should not throw a CancelledError when fetchQuery is in progress and the last observer unsubscribes when AbortSignal is consumed', async () => {
235 const key = queryKey()
236β
237 const observer = new QueryObserver(queryClient, {
238 queryKey: key,
239 queryFn: () => sleep(100).then(() => 'data'),
240 })
241β
242 const unsubscribe = observer.subscribe(() => undefined)
243 await vi.advanceTimersByTimeAsync(100)
244β
245 expect(queryCache.find({ queryKey: key })?.state.data).toBe('data')
246β
247 const promise = queryClient.fetchQuery({
248 queryKey: key,
249 queryFn: ({ signal }) => sleep(100).then(() => 'data2' + String(signal)),
250 })
251β
252 // Ensure the fetch is in progress
253 await vi.advanceTimersByTimeAsync(10)
254β
255 // Unsubscribe while fetch is in progress
256 unsubscribe()
257 // await queryClient.cancelQueries()
258β
259 await vi.advanceTimersByTimeAsync(90)
260β
261 // Fetch should complete successfully without throwing a CancelledError
262 await expect(promise).resolves.toBe('data')
263β
264 expect(queryCache.find({ queryKey: key })?.state.data).toBe('data')
265 })
266β
267 it('should provide context to queryFn', () => {
268 const key = queryKey()
269β
270 const queryFn = vi
271 .fn<
272 (
273 context: QueryFunctionContext<ReturnType<typeof queryKey>>,
274 ) => Promise<'data'>
275 >()
276 .mockResolvedValue('data')
277β
278 queryClient.prefetchQuery({ queryKey: key, queryFn })
279β
280 expect(queryFn).toHaveBeenCalledTimes(1)
281 const args = queryFn.mock.calls[0]![0]
282 expect(args.pageParam).toBeUndefined()
283 expect(args.queryKey).toEqual(key)
284 expect(args.signal).toBeInstanceOf(AbortSignal)
285 expect(args.client).toEqual(queryClient)
286 })
287β
288 it('should continue if cancellation is not supported and signal is not consumed', async () => {
289 const key = queryKey()
290β
291 queryClient.prefetchQuery({
292 queryKey: key,
293 queryFn: () => sleep(100).then(() => 'data'),
294 })
295β
296 await vi.advanceTimersByTimeAsync(10)
297β
298 // Subscribe and unsubscribe to simulate cancellation because the last observer unsubscribed
299 const observer = new QueryObserver(queryClient, {
300 queryKey: key,
301 enabled: false,
302 })
303 const unsubscribe = observer.subscribe(() => undefined)
304 unsubscribe()
305β
306 await vi.advanceTimersByTimeAsync(90)
307β
308 const query = queryCache.find({ queryKey: key })!
309β
310 expect(query.state).toMatchObject({
311 data: 'data',
312 status: 'success',
313 dataUpdateCount: 1,
314 })
315 })
316β
317 it('should not continue when last observer unsubscribed if the signal was consumed', async () => {
318 const key = queryKey()
319β
320 queryClient.prefetchQuery({
321 queryKey: key,
322 queryFn: ({ signal }) =>
323 sleep(100).then(() => (signal.aborted ? 'aborted' : 'data')),
324 })
325β
326 await vi.advanceTimersByTimeAsync(10)
327β
328 // Subscribe and unsubscribe to simulate cancellation because the last observer unsubscribed
329 const observer = new QueryObserver(queryClient, {
330 queryKey: key,
331 enabled: false,
332 })
333 const unsubscribe = observer.subscribe(() => undefined)
334 unsubscribe()
335β
336 await vi.advanceTimersByTimeAsync(90)
337β
338 const query = queryCache.find({ queryKey: key })!
339β
340 expect(query.state).toMatchObject({
341 data: undefined,
342 status: 'pending',
343 fetchStatus: 'idle',
344 })
345 })
346β
347 it('should provide an AbortSignal to the queryFn that provides info about the cancellation state', async () => {
348 const key = queryKey()
349β
350 const queryFn =
351 vi.fn<
352 (
353 context: QueryFunctionContext<ReturnType<typeof queryKey>>,
354 ) => Promise<unknown>
355 >()
356 const onAbort = vi.fn()
357 const abortListener = vi.fn()
358 let error
359β
360 queryFn.mockImplementation(async ({ signal }) => {
361 signal.onabort = onAbort
362 signal.addEventListener('abort', abortListener)
363 await sleep(10)
364 signal.onabort = null
365 signal.removeEventListener('abort', abortListener)
366 throw new Error()
367 })
368β
369 const promise = queryClient.fetchQuery({
370 queryKey: key,
371 queryFn,
372 retry: 3,
373 retryDelay: 10,
374 })
375β
376 promise.catch((e) => {
377 error = e
378 })
379β
380 const query = queryCache.find({ queryKey: key })!
381β
382 expect(queryFn).toHaveBeenCalledTimes(1)
383β
384 const signal = queryFn.mock.calls[0]![0].signal
385 expect(signal.aborted).toBe(false)
386 expect(onAbort).not.toHaveBeenCalled()
387 expect(abortListener).not.toHaveBeenCalled()
388β
389 query.cancel()
390β
391 await vi.advanceTimersByTimeAsync(100)
392β
393 expect(signal.aborted).toBe(true)
394 expect(onAbort).toHaveBeenCalledTimes(1)
395 expect(abortListener).toHaveBeenCalledTimes(1)
396 expect(error).toBeInstanceOf(CancelledError)
397 })
398β
399 it('should not continue if explicitly cancelled', async () => {
400 const key = queryKey()
401β
402 const queryFn = vi.fn<(...args: Array<unknown>) => unknown>()
403β
404 queryFn.mockImplementation(async () => {
405 await sleep(10)
406 throw new Error()
407 })
408β
409 let error
410β
411 const promise = queryClient.fetchQuery({
412 queryKey: key,
413 queryFn,
414 retry: 3,
415 retryDelay: 10,
416 })
417β
418 promise.catch((e) => {
419 error = e
420 })
421β
422 const query = queryCache.find({ queryKey: key })!
423 query.cancel()
424β
425 await vi.advanceTimersByTimeAsync(100)
426β
427 expect(queryFn).toHaveBeenCalledTimes(1)
428 expect(error).toBeInstanceOf(CancelledError)
429 })
430β
431 it('should not error if reset while pending', async () => {
432 const key = queryKey()
433β
434 const queryFn = vi.fn<(...args: Array<unknown>) => unknown>()
435β
436 queryFn.mockImplementation(async () => {
437 await sleep(10)
438 throw new Error()
439 })
440β
441 let error
442β
443 queryClient
444 .fetchQuery({
445 queryKey: key,
446 queryFn,
447 retry: 3,
448 retryDelay: 10,
449 })
450 .catch((e) => {
451 error = e
452 })
453β
454 // Ensure the query is pending
455 const query = queryCache.find({ queryKey: key })!
456 expect(query.state.status).toBe('pending')
457β
458 // Reset the query while it is pending
459 query.reset()
460β
461 await vi.advanceTimersByTimeAsync(100)
462β
463 // The query should
464 expect(queryFn).toHaveBeenCalledTimes(1) // have been called,
465 expect(query.state.error).toBe(null) // not have an error, and
466 expect(query.state.fetchStatus).toBe('idle') // not be loading any longer
467 expect(query.state.data).toBe(undefined) // have no data
468β
469 // the call to fetchQuery must reject
470 // because it was reset and not reverted
471 // so it would resolve with undefined otherwise
472 expect(error).toBeInstanceOf(CancelledError)
473 })
474β
475 it('should reset to default state when created from hydration', async () => {
476 const key = queryKey()
477 const client = new QueryClient()
478 await client.prefetchQuery({
479 queryKey: key,
480 queryFn: () => Promise.resolve('string'),
481 })
482β
483 const dehydrated = dehydrate(client)
484β
485 const hydrationClient = new QueryClient()
486 hydrate(hydrationClient, dehydrated)
487β
488 expect(hydrationClient.getQueryData(key)).toBe('string')
489β
490 const query = hydrationClient.getQueryCache().find({ queryKey: key })
491 query?.reset()
492β
493 expect(hydrationClient.getQueryData(key)).toBe(undefined)
494 })
495β
496 it('should be able to refetch a cancelled query', async () => {
497 const key = queryKey()
498β
499 const queryFn = vi.fn<(...args: Array<unknown>) => unknown>()
500β
501 queryFn.mockImplementation(() => sleep(50).then(() => 'data'))
502β
503 queryClient.prefetchQuery({ queryKey: key, queryFn })
504 const query = queryCache.find({ queryKey: key })!
505 await vi.advanceTimersByTimeAsync(10)
506 query.cancel()
507 await vi.advanceTimersByTimeAsync(100)
508β
509 expect(queryFn).toHaveBeenCalledTimes(1)
510 expect(query.state.error).toBeInstanceOf(CancelledError)
511 const result = query.fetch()
512 await vi.advanceTimersByTimeAsync(50)
513 await expect(result).resolves.toBe('data')
514 expect(query.state.error).toBe(null)
515 expect(queryFn).toHaveBeenCalledTimes(2)
516 })
517β
518 it('cancelling a resolved query should not have any effect', async () => {
519 const key = queryKey()
520 await queryClient.prefetchQuery({
521 queryKey: key,
522 queryFn: () => 'data',
523 })
524 const query = queryCache.find({ queryKey: key })!
525 query.cancel()
526 await vi.advanceTimersByTimeAsync(10)
527 expect(query.state.data).toBe('data')
528 })
529β
530 it('cancelling a rejected query should not have any effect', async () => {
531 const key = queryKey()
532 const error = new Error('error')
533β
534 await queryClient.prefetchQuery({
535 queryKey: key,
536 queryFn: () => Promise.reject(error),
537 })
538 const query = queryCache.find({ queryKey: key })!
539 query.cancel()
540 await vi.advanceTimersByTimeAsync(10)
541β
542 expect(query.state.error).toBe(error)
543 expect(query.state.error).not.toBeInstanceOf(CancelledError)
544 })
545β
546 it('the previous query status should be kept when refetching', async () => {
547 const key = queryKey()
548β
549 await queryClient.prefetchQuery({ queryKey: key, queryFn: () => 'data' })
550 const query = queryCache.find({ queryKey: key })!
551 expect(query.state.status).toBe('success')
552β
553 await queryClient.prefetchQuery({
554 queryKey: key,
555 queryFn: () => Promise.reject<string>('reject'),
556 retry: false,
557 })
558 expect(query.state.status).toBe('error')
559β
560 queryClient.prefetchQuery({
561 queryKey: key,
562 queryFn: () => sleep(10).then(() => Promise.reject<unknown>('reject')),
563 retry: false,
564 })
565 expect(query.state.status).toBe('error')
566β
567 await vi.advanceTimersByTimeAsync(10)
568 expect(query.state.status).toBe('error')
569 })
570β
571 it('queries with gcTime 0 should be removed immediately after unsubscribing', async () => {
572 const key = queryKey()
573 let count = 0
574 const observer = new QueryObserver(queryClient, {
575 queryKey: key,
576 queryFn: () => {
577 count++
578 return 'data'
579 },
580 gcTime: 0,
581 staleTime: Infinity,
582 })
583 const unsubscribe1 = observer.subscribe(() => undefined)
584 unsubscribe1()
585β
586 await vi.advanceTimersByTimeAsync(0)
587 expect(queryCache.find({ queryKey: key })).toBeUndefined()
588 const unsubscribe2 = observer.subscribe(() => undefined)
589 unsubscribe2()
590β
591 await vi.advanceTimersByTimeAsync(0)
592 expect(queryCache.find({ queryKey: key })).toBeUndefined()
593 expect(count).toBe(1)
594 })
595β
596 it('should be garbage collected when unsubscribed to', async () => {
597 const key = queryKey()
598 const observer = new QueryObserver(queryClient, {
599 queryKey: key,
600 queryFn: () => 'data',
601 gcTime: 0,
602 })
603 expect(queryCache.find({ queryKey: key })?.state.status).toBe('pending')
604 const unsubscribe = observer.subscribe(() => undefined)
605 expect(queryCache.find({ queryKey: key })?.state.status).toBe('pending')
606 unsubscribe()
607β
608 await vi.advanceTimersByTimeAsync(0)
609 expect(queryCache.find({ queryKey: key })).toBeUndefined()
610 })
611β
612 it('should be garbage collected later when unsubscribed and query is fetching', async () => {
613 const key = queryKey()
614 const observer = new QueryObserver(queryClient, {
615 queryKey: key,
616 queryFn: () => sleep(20).then(() => 'data'),
617 gcTime: 10,
618 })
619 const unsubscribe = observer.subscribe(() => undefined)
620 await vi.advanceTimersByTimeAsync(20)
621 expect(queryCache.find({ queryKey: key })?.state.data).toBe('data')
622 observer.refetch()
623 unsubscribe()
624 // unsubscribe should not remove even though gcTime has elapsed b/c query is still fetching
625 expect(queryCache.find({ queryKey: key })?.state.data).toBe('data')
626 // should be removed after an additional staleTime wait
627 await vi.advanceTimersByTimeAsync(30)
628 expect(queryCache.find({ queryKey: key })).toBeUndefined()
629 })
630β
631 it('should not be garbage collected unless there are no subscribers', async () => {
632 const key = queryKey()
633 const observer = new QueryObserver(queryClient, {
634 queryKey: key,
635 queryFn: () => 'data',
636 gcTime: 0,
637 })
638 expect(queryCache.find({ queryKey: key })?.state.status).toBe('pending')
639 const unsubscribe = observer.subscribe(() => undefined)
640 await vi.advanceTimersByTimeAsync(100)
641 expect(queryCache.find({ queryKey: key })?.state.data).toBe('data')
642 unsubscribe()
643 await vi.advanceTimersByTimeAsync(100)
644 expect(queryCache.find({ queryKey: key })).toBeUndefined()
645 queryClient.setQueryData(key, 'data')
646 await vi.advanceTimersByTimeAsync(100)
647 expect(queryCache.find({ queryKey: key })?.state.data).toBe('data')
648 })
649β
650 it('should return proper count of observers', () => {
651 const key = queryKey()
652 const options = { queryKey: key, queryFn: () => 'data' }
653 const observer = new QueryObserver(queryClient, options)
654 const observer2 = new QueryObserver(queryClient, options)
655 const observer3 = new QueryObserver(queryClient, options)
656 const query = queryCache.find({ queryKey: key })
657β
658 expect(query?.getObserversCount()).toEqual(0)
659β
660 const unsubscribe1 = observer.subscribe(() => undefined)
661 const unsubscribe2 = observer2.subscribe(() => undefined)
662 const unsubscribe3 = observer3.subscribe(() => undefined)
663 expect(query?.getObserversCount()).toEqual(3)
664β
665 unsubscribe3()
666 expect(query?.getObserversCount()).toEqual(2)
667β
668 unsubscribe2()
669 expect(query?.getObserversCount()).toEqual(1)
670β
671 unsubscribe1()
672 expect(query?.getObserversCount()).toEqual(0)
673 })
674β
675 it('stores meta object in query', async () => {
676 const meta = {
677 it: 'works',
678 }
679β
680 const key = queryKey()
681β
682 await queryClient.prefetchQuery({
683 queryKey: key,
684 queryFn: () => 'data',
685 meta,
686 })
687β
688 const query = queryCache.find({ queryKey: key })!
689β
690 expect(query.meta).toBe(meta)
691 expect(query.options.meta).toBe(meta)
692 })
693β
694 it('updates meta object on change', async () => {
695 const meta = {
696 it: 'works',
697 }
698β
699 const key = queryKey()
700 const queryFn = () => 'data'
701β
702 await queryClient.prefetchQuery({ queryKey: key, queryFn, meta })
703β
704 await queryClient.prefetchQuery({ queryKey: key, queryFn, meta: undefined })
705β
706 const query = queryCache.find({ queryKey: key })!
707β
708 expect(query.meta).toBeUndefined()
709 expect(query.options.meta).toBeUndefined()
710 })
711β
712 it('can use default meta', async () => {
713 const meta = {
714 it: 'works',
715 }
716β
717 const key = queryKey()
718 const queryFn = () => 'data'
719β
720 queryClient.setQueryDefaults(key, { meta })
721β
722 await queryClient.prefetchQuery({ queryKey: key, queryFn })
723β
724 const query = queryCache.find({ queryKey: key })!
725β
726 expect(query.meta).toBe(meta)
727 })
728β
729 it('provides meta object inside query function', async () => {
730 const meta = {
731 it: 'works',
732 }
733β
734 const queryFn = vi.fn(() => 'data')
735β
736 const key = queryKey()
737β
738 await queryClient.prefetchQuery({ queryKey: key, queryFn, meta })
739β
740 expect(queryFn).toHaveBeenCalledWith(
741 expect.objectContaining({
742 meta,
743 }),
744 )
745 })
746β
747 it('should refetch the observer when online method is called', () => {
748 const key = queryKey()
749β
750 const observer = new QueryObserver(queryClient, {
751 queryKey: key,
752 queryFn: () => 'data',
753 })
754β
755 const refetchSpy = vi.spyOn(observer, 'refetch')
756 const unsubscribe = observer.subscribe(() => undefined)
757 queryCache.onOnline()
758β
759 // Should refetch the observer
760 expect(refetchSpy).toHaveBeenCalledTimes(1)
761β
762 unsubscribe()
763 refetchSpy.mockRestore()
764 })
765β
766 it('should not add an existing observer', async () => {
767 const key = queryKey()
768β
769 await queryClient.prefetchQuery({ queryKey: key, queryFn: () => 'data' })
770 const query = queryCache.find({ queryKey: key })!
771 expect(query.getObserversCount()).toEqual(0)
772β
773 const observer = new QueryObserver(queryClient, {
774 queryKey: key,
775 })
776 expect(query.getObserversCount()).toEqual(0)
777β
778 query.addObserver(observer)
779 expect(query.getObserversCount()).toEqual(1)
780β
781 query.addObserver(observer)
782 expect(query.getObserversCount()).toEqual(1)
783 })
784β
785 it('should not try to remove an observer that does not exist', async () => {
786 const key = queryKey()
787β
788 await queryClient.prefetchQuery({ queryKey: key, queryFn: () => 'data' })
789 const query = queryCache.find({ queryKey: key })!
790 const observer = new QueryObserver(queryClient, {
791 queryKey: key,
792 })
793 expect(query.getObserversCount()).toEqual(0)
794β
795 const notifySpy = vi.spyOn(queryCache, 'notify')
796 expect(() => query.removeObserver(observer)).not.toThrow()
797 expect(notifySpy).not.toHaveBeenCalled()
798β
799 notifySpy.mockRestore()
800 })
801β
802 it('should not change state on invalidate() if already invalidated', async () => {
803 const key = queryKey()
804β
805 await queryClient.prefetchQuery({ queryKey: key, queryFn: () => 'data' })
806 const query = queryCache.find({ queryKey: key })!
807β
808 query.invalidate()
809 expect(query.state.isInvalidated).toBe(true)
810β
811 const previousState = query.state
812β
813 query.invalidate()
814β
815 expect(query.state).toBe(previousState)
816 })
817β
818 it('fetch should not dispatch "fetch" query is already fetching', async () => {
819 const key = queryKey()
820β
821 const queryFn = () => sleep(10).then(() => 'data')
822β
823 const updates: Array<string> = []
824β
825 queryClient.prefetchQuery({ queryKey: key, queryFn })
826 await vi.advanceTimersByTimeAsync(10)
827 const query = queryCache.find({ queryKey: key })!
828β
829 const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
830 updates.push(event.type)
831 })
832β
833 void query.fetch({
834 queryKey: key,
835 queryFn,
836 })
837β
838 query.fetch({
839 queryKey: key,
840 queryFn,
841 })
842 await vi.advanceTimersByTimeAsync(10)
843β
844 expect(updates).toEqual([
845 'updated', // type: 'fetch'
846 'updated', // type: 'success'
847 ])
848 unsubscribe()
849 })
850β
851 it('fetch should throw an error if the queryFn is not defined', async () => {
852 const key = queryKey()
853β
854 const observer = new QueryObserver(queryClient, {
855 queryKey: key,
856 queryFn: undefined,
857 retry: false,
858 })
859β
860 const unsubscribe = observer.subscribe(() => undefined)
861β
862 await vi.advanceTimersByTimeAsync(10)
863 const query = queryCache.find({ queryKey: key })!
864 expect(observer.getCurrentResult()).toMatchObject({
865 status: 'error',
866 error: new Error(`Missing queryFn: '${query.queryHash}'`),
867 })
868 unsubscribe()
869 })
870β
871 it('fetch should dispatch an error if the queryFn returns undefined', async () => {
872 const consoleMock = vi.spyOn(console, 'error')
873 consoleMock.mockImplementation(() => undefined)
874 const key = queryKey()
875β
876 const observer = new QueryObserver(queryClient, {
877 queryKey: key,
878 queryFn: () => undefined,
879 retry: false,
880 })
881β
882 let observerResult: QueryObserverResult<unknown, unknown> | undefined
883β
884 const unsubscribe = observer.subscribe((result) => {
885 observerResult = result
886 })
887β
888 await vi.advanceTimersByTimeAsync(10)
889β
890 const error = new Error(`${JSON.stringify(key)} data is undefined`)
891β
892 expect(observerResult).toMatchObject({
893 isError: true,
894 error,
895 })
896β
897 expect(consoleMock).toHaveBeenCalledWith(
898 `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ["${key}"]`,
899 )
900 unsubscribe()
901 consoleMock.mockRestore()
902 })
903β
904 it('should not retry on the server', async () => {
905 const resetIsServer = setIsServer(true)
906β
907 const key = queryKey()
908 let count = 0
909β
910 const observer = new QueryObserver(queryClient, {
911 queryKey: key,
912 queryFn: () => {
913 count++
914 return Promise.reject(new Error('error'))
915 },
916 })
917β
918 await observer.refetch()
919β
920 expect(count).toBe(1)
921β
922 resetIsServer()
923 })
924β
925 it('constructor should call initialDataUpdatedAt if defined as a function', async () => {
926 const key = queryKey()
927β
928 const initialDataUpdatedAtSpy = vi.fn()
929β
930 await queryClient.prefetchQuery({
931 queryKey: key,
932 queryFn: () => 'data',
933 initialData: 'initial',
934 initialDataUpdatedAt: initialDataUpdatedAtSpy,
935 })
936β
937 expect(initialDataUpdatedAtSpy).toHaveBeenCalled()
938 })
939β
940 it('should work with initialDataUpdatedAt set to zero', async () => {
941 const key = queryKey()
942β
943 await queryClient.prefetchQuery({
944 queryKey: key,
945 queryFn: () => 'data',
946 staleTime: Infinity,
947 initialData: 'initial',
948 initialDataUpdatedAt: 0,
949 })
950β
951 expect(queryCache.find({ queryKey: key })?.state).toMatchObject({
952 data: 'initial',
953 status: 'success',
954 dataUpdatedAt: 0,
955 })
956 })
957β
958 it('queries should be garbage collected even if they never fetched', async () => {
959 const key = queryKey()
960β
961 queryClient.setQueryDefaults(key, { gcTime: 10 })
962β
963 const fn = vi.fn()
964β
965 const unsubscribe = queryClient.getQueryCache().subscribe(fn)
966β
967 queryClient.setQueryData(key, 'data')
968 const query = queryClient.getQueryCache().find({ queryKey: key })
969β
970 await vi.advanceTimersByTimeAsync(10)
971 expect(fn).toHaveBeenLastCalledWith({ type: 'removed', query })
972β
973 expect(queryClient.getQueryCache().findAll()).toHaveLength(0)
974β
975 unsubscribe()
976 })
977β
978 it('should always revert to idle state (#5968)', async () => {
979 let mockedData = [1]
980β
981 const key = queryKey()
982β
983 const queryFn = vi
984 .fn<
985 (
986 context: QueryFunctionContext<ReturnType<typeof queryKey>>,
987 ) => Promise<unknown>
988 >()
989 .mockImplementation(
990 ({ signal }) =>
991 new Promise((resolve, reject) => {
992 const abortListener = () => {
993 clearTimeout(timerId)
994 reject(signal.reason)
995 }
996 signal.addEventListener('abort', abortListener)
997β
998 const timerId = setTimeout(() => {
999 signal.removeEventListener('abort', abortListener)
1000 resolve(mockedData.join(' - '))
1001 }, 50)
1002 }),
1003 )
1004β
1005 const observer = new QueryObserver(queryClient, {
1006 queryKey: key,
1007 queryFn,
1008 })
1009 const unsubscribe = observer.subscribe(() => undefined)
1010 await vi.advanceTimersByTimeAsync(50) // let it resolve
1011β
1012 expect(observer.getCurrentResult().data).toBe('1')
1013 expect(observer.getCurrentResult().fetchStatus).toBe('idle')
1014β
1015 mockedData = [1, 2] // update "server" state in the background
1016β
1017 void queryClient.invalidateQueries({ queryKey: key })
1018 await vi.advanceTimersByTimeAsync(5)
1019 void queryClient.invalidateQueries({ queryKey: key })
1020 await vi.advanceTimersByTimeAsync(5)
1021 unsubscribe() // unsubscribe to simulate unmount
1022 await vi.advanceTimersByTimeAsync(5)
1023β
1024 // reverted to previous data and idle fetchStatus
1025 expect(queryCache.find({ queryKey: key })?.state).toMatchObject({
1026 status: 'success',
1027 data: '1',
1028 fetchStatus: 'idle',
1029 })
1030β
1031 // set up a new observer to simulate a mount of new component
1032 const newObserver = new QueryObserver(queryClient, {
1033 queryKey: key,
1034 queryFn,
1035 })
1036 const spy = vi.fn()
1037 newObserver.subscribe(({ data }) => spy(data))
1038 await vi.advanceTimersByTimeAsync(60) // let it resolve
1039 expect(spy).toHaveBeenCalledWith('1 - 2')
1040 })
1041β
1042 it('should not reject a promise when silently cancelled in the background', async () => {
1043 const key = queryKey()
1044β
1045 let x = 0
1046β
1047 queryClient.setQueryData(key, 'initial')
1048 const queryFn = vi
1049 .fn()
1050 .mockImplementation(() => sleep(100).then(() => 'data' + x))
1051β
1052 const promise = queryClient.fetchQuery({
1053 queryKey: key,
1054 queryFn,
1055 })
1056β
1057 await vi.advanceTimersByTimeAsync(0)
1058 expect(queryFn).toHaveBeenCalledTimes(1)
1059β
1060 x = 1
1061β
1062 // cancel ongoing re-fetches
1063 void queryClient.refetchQueries({ queryKey: key }, { cancelRefetch: true })
1064β
1065 // The promise should not reject
1066 await vi.advanceTimersByTimeAsync(100)
1067 await expect(promise).resolves.toBe('data1')
1068β
1069 expect(queryFn).toHaveBeenCalledTimes(2)
1070 })
1071β
1072 it('should have an error log when queryFn data is not serializable', async () => {
1073 const consoleMock = vi.spyOn(console, 'error')
1074β
1075 consoleMock.mockImplementation(() => undefined)
1076β
1077 const key = queryKey()
1078β
1079 const queryFn = vi.fn()
1080β
1081 const initialData = {
1082 foo: 'bar',
1083 }
1084β
1085 const data = {
1086 get foo(): void {
1087 return this.foo
1088 },
1089 }
1090β
1091 queryFn.mockImplementation(() => sleep(10).then(() => data))
1092β
1093 queryClient.prefetchQuery({
1094 queryKey: key,
1095 queryFn,
1096 initialData,
1097 })
1098 await vi.advanceTimersByTimeAsync(10)
1099β
1100 const query = queryCache.find({ queryKey: key })!
1101β
1102 expect(queryFn).toHaveBeenCalledTimes(1)
1103β
1104 expect(query.state.status).toBe('error')
1105 expect(query.state.error?.message).toContain(
1106 'Maximum call stack size exceeded',
1107 )
1108β
1109 expect(consoleMock).toHaveBeenCalledWith(
1110 expect.stringContaining(
1111 'Structural sharing requires data to be JSON serializable',
1112 ),
1113 )
1114β
1115 consoleMock.mockRestore()
1116 })
1117β
1118 it('should have an error status when setData has any error inside', async () => {
1119 const key = queryKey()
1120β
1121 const queryFn = vi
1122 .fn<() => Promise<string>>()
1123 .mockImplementation(() => sleep(10).then(() => 'data'))
1124β
1125 queryClient.prefetchQuery({
1126 queryKey: key,
1127 queryFn,
1128 structuralSharing: () => {
1129 throw Error('Any error')
1130 },
1131 })
1132β
1133 const query = queryCache.find({ queryKey: key })!
1134β
1135 expect(queryFn).toHaveBeenCalledTimes(1)
1136 await vi.advanceTimersByTimeAsync(10)
1137 expect(query.state.status).toBe('error')
1138 })
1139β
1140 it('should use persister if provided', async () => {
1141 const key = queryKey()
1142β
1143 await queryClient.prefetchQuery({
1144 queryKey: key,
1145 queryFn: () => 'data',
1146 persister: () => Promise.resolve('persisted data'),
1147 })
1148β
1149 const query = queryCache.find({ queryKey: key })!
1150 expect(query.state.data).toBe('persisted data')
1151 })
1152β
1153 it('should use queryFn from observer if not provided in options', async () => {
1154 const key = queryKey()
1155 const queryFn = () => Promise.resolve('data')
1156 const observer = new QueryObserver(queryClient, {
1157 queryKey: key,
1158 queryFn: queryFn,
1159 })
1160β
1161 const query = new Query({
1162 client: queryClient,
1163 queryKey: key,
1164 queryHash: hashQueryKeyByOptions(key),
1165 })
1166β
1167 query.addObserver(observer)
1168β
1169 await query.fetch()
1170 const result = await query.state.data
1171 expect(result).toBe('data')
1172 expect(query.options.queryFn).toBe(queryFn)
1173 })
1174β
1175 it('should log error when queryKey is not an array', async () => {
1176 const consoleMock = vi.spyOn(console, 'error')
1177 const key: unknown = 'string-key'
1178β
1179 await queryClient.prefetchQuery({
1180 queryKey: key as QueryKey,
1181 queryFn: () => 'data',
1182 })
1183β
1184 expect(consoleMock).toHaveBeenCalledWith(
1185 "As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']",
1186 )
1187β
1188 consoleMock.mockRestore()
1189 })
1190β
1191 it('should call initialData function when it is a function', () => {
1192 const key = queryKey()
1193 const initialDataFn = vi.fn(() => 'initial data')
1194β
1195 const query = new Query({
1196 client: queryClient,
1197 queryKey: key,
1198 queryHash: hashQueryKeyByOptions(key),
1199 options: {
1200 queryFn: () => 'data',
1201 initialData: initialDataFn,
1202 },
1203 })
1204β
1205 expect(initialDataFn).toHaveBeenCalledTimes(1)
1206 expect(query.state.data).toBe('initial data')
1207 })
1208β
1209 it('should update initialData when Query exists without data', async () => {
1210 const key = queryKey()
1211 const queryFn = vi.fn(() => sleep(100).then(() => 'data'))
1212β
1213 const promise = queryClient.prefetchQuery({
1214 queryKey: key,
1215 queryFn,
1216 staleTime: 1000,
1217 })
1218β
1219 vi.advanceTimersByTime(50)
1220β
1221 expect(queryClient.getQueryState(key)).toMatchObject({
1222 data: undefined,
1223 status: 'pending',
1224 fetchStatus: 'fetching',
1225 })
1226β
1227 const observer = new QueryObserver(queryClient, {
1228 queryKey: key,
1229 queryFn,
1230 staleTime: 1000,
1231 initialData: 'initialData',
1232 initialDataUpdatedAt: 10,
1233 })
1234β
1235 const unsubscribe = observer.subscribe(vi.fn())
1236β
1237 expect(queryClient.getQueryState(key)).toMatchObject({
1238 data: 'initialData',
1239 dataUpdatedAt: 10,
1240 status: 'success',
1241 fetchStatus: 'fetching',
1242 })
1243β
1244 vi.advanceTimersByTime(50)
1245β
1246 await promise
1247β
1248 expect(queryClient.getQueryState(key)).toMatchObject({
1249 data: 'data',
1250 status: 'success',
1251 fetchStatus: 'idle',
1252 })
1253β
1254 expect(queryFn).toHaveBeenCalledTimes(1)
1255β
1256 unsubscribe()
1257β
1258 // resetting should get us back ot 'initialData'
1259 queryClient.getQueryCache().find({ queryKey: key })!.reset()
1260β
1261 expect(queryClient.getQueryState(key)).toMatchObject({
1262 data: 'initialData',
1263 status: 'success',
1264 fetchStatus: 'idle',
1265 })
1266 })
1267β
1268 it('should not override fetching state when revert happens after new observer subscribes', async () => {
1269 const key = queryKey()
1270 let count = 0
1271β
1272 const queryFn = vi.fn(async ({ signal: _signal }) => {
1273 // Destructure `signal` to intentionally consume it so observer-removal uses revert-cancel path
1274 await sleep(50)
1275 return 'data' + count++
1276 })
1277β
1278 const query = new Query({
1279 client: queryClient,
1280 queryKey: key,
1281 queryHash: hashQueryKeyByOptions(key),
1282 options: { queryFn },
1283 })
1284β
1285 const observer1 = new QueryObserver(queryClient, {
1286 queryKey: key,
1287 queryFn,
1288 })
1289β
1290 query.addObserver(observer1)
1291 const promise1 = query.fetch()
1292β
1293 await vi.advanceTimersByTimeAsync(10)
1294β
1295 query.removeObserver(observer1)
1296β
1297 const observer2 = new QueryObserver(queryClient, {
1298 queryKey: key,
1299 queryFn,
1300 })
1301β
1302 query.addObserver(observer2)
1303β
1304 query.fetch()
1305β
1306 await expect(promise1).rejects.toBeInstanceOf(CancelledError)
1307 await vi.advanceTimersByTimeAsync(50)
1308 expect(query.state.fetchStatus).toBe('idle')
1309β
1310 expect(queryFn).toHaveBeenCalledTimes(2)
1311β
1312 expect(query.state).toMatchObject({
1313 fetchStatus: 'idle',
1314 status: 'success',
1315 data: 'data1',
1316 })
1317 })
1318β
1319 it('should not increment dataUpdateCount when setting initialData on prefetched query', async () => {
1320 const key = queryKey()
1321 const queryFn = vi.fn().mockImplementation(() => 'fetched-data')
1322β
1323 // First prefetch the query (creates query without data)
1324 queryClient.prefetchQuery({
1325 queryKey: key,
1326 queryFn,
1327 })
1328β
1329 const query = queryCache.find({ queryKey: key })!
1330 expect(query.state.data).toBeUndefined()
1331 expect(query.state.dataUpdateCount).toBe(0)
1332β
1333 // Now create an observer with initialData
1334 const observer = new QueryObserver(queryClient, {
1335 queryKey: key,
1336 queryFn,
1337 initialData: 'initial-data',
1338 })
1339β
1340 // The query should now have the initial data but dataUpdateCount should still be 0
1341 // since this was not fetched data but initial data
1342 expect(query.state.data).toBe('initial-data')
1343 expect(query.state.dataUpdateCount).toBe(0)
1344β
1345 // Get the initial state as captured by the observer
1346 const result = observer.getCurrentResult()
1347 expect(result.data).toBe('initial-data')
1348 expect(result.isFetchedAfterMount).toBe(false) // This should be false since no actual fetch occurred
1349β
1350 // Now trigger a refetch through the observer to simulate real-world usage
1351 await observer.refetch()
1352β
1353 // After actual fetch, dataUpdateCount should increment
1354 expect(query.state.dataUpdateCount).toBe(1)
1355 expect(query.state.data).toBe('fetched-data')
1356β
1357 // And isFetchedAfterMount should now be true
1358 const updatedResult = observer.getCurrentResult()
1359 expect(updatedResult.isFetchedAfterMount).toBe(true)
1360 })
1361})