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 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',
1054 }
1055β
1056 const data = {
1057 get foo(): void {
1058 return this.foo
1059 },
1060 }
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 ),
1084 )
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']",
1157 )
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 })
1334})