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

query.test.tsx

1,307 lines34.2 KB

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