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

query.test.tsx

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