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

query.test.tsx

1,361 lines36.2 KB

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 }),
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',
1084​
1085 const data = {
1086 get foo(): void {
1087 return this.foo
1088 },
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',
1108​
1109 expect(consoleMock).toHaveBeenCalledWith(
1110 expect.stringContaining(
1111 'Structural sharing requires data to be JSON serializable',
1112 ),
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']",
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 })