Open History to see the last commit
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]
1076 }
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 ),
1100 )
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']",
1173 )
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 })
1307})