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

query.test.tsx

1,023 lines26.9 KB

1import { afterEach, beforeEach, describe, expect, it, test, vi } from 'vitest'
2import { QueryObserver, dehydrate, hydrate, isCancelledError } from '..'
3import {
4 createQueryClient,
5 mockOnlineManagerIsOnline,
6 mockVisibilityState,
7 queryKey,
8 setIsServer,
9 sleep,
10} from './utils'
11import type {
12 QueryCache,
13 QueryClient,
14 QueryFunctionContext,
15 QueryObserverResult,
16} from '..'
17​
18describe('query', () => {
19 let queryClient: QueryClient
20 let queryCache: QueryCache
21​
22 beforeEach(() => {
23 vi.useFakeTimers()
24 queryClient = createQueryClient()
25 queryCache = queryClient.getQueryCache()
26 queryClient.mount()
27 })
28​
29 afterEach(() => {
30 queryClient.clear()
31 vi.useRealTimers()
32 })
33​
34 test('should use the longest garbage collection time it has seen', async () => {
35 const key = queryKey()
36 await queryClient.prefetchQuery({
37 queryKey: key,
38 queryFn: () => 'data',
39 gcTime: 100,
40 })
41 await queryClient.prefetchQuery({
42 queryKey: key,
43 queryFn: () => 'data',
44 gcTime: 200,
45 })
46 await queryClient.prefetchQuery({
47 queryKey: key,
48 queryFn: () => 'data',
49 gcTime: 10,
50 })
51 const query = queryCache.find({ queryKey: key })!
52 expect(query.gcTime).toBe(200)
53 })
54​
55 it('should continue retry after focus regain and resolve all promises', async () => {
56 const key = queryKey()
57​
58 // make page unfocused
59 const visibilityMock = mockVisibilityState('hidden')
60​
61 let count = 0
62 let result
63​
64 const promise = queryClient.fetchQuery({
65 queryKey: key,
66 queryFn: () => {
67 count++
68​
69 if (count === 3) {
70 return `data${count}`
71 }
72​
73 throw new Error(`error${count}`)
74 },
75 retry: 3,
76 retryDelay: 1,
77 })
78​
79 promise.then((data) => {
80 result = data
81 })
82​
83 // Check if we do not have a result
84 expect(result).toBeUndefined()
85​
86 // Check if the query is really paused
87 await vi.advanceTimersByTimeAsync(50)
88 expect(result).toBeUndefined()
89​
90 // Reset visibilityState to original value
91 visibilityMock.mockRestore()
92 window.dispatchEvent(new Event('visibilitychange'))
93​
94 // There should not be a result yet
95 expect(result).toBeUndefined()
96​
97 // By now we should have a value
98 await vi.advanceTimersByTimeAsync(50)
99 expect(result).toBe('data3')
100 })
101​
102 it('should continue retry after reconnect and resolve all promises', async () => {
103 const key = queryKey()
104​
105 const onlineMock = mockOnlineManagerIsOnline(false)
106​
107 let count = 0
108 let result
109​
110 const promise = queryClient.fetchQuery({
111 queryKey: key,
112 queryFn: () => {
113 count++
114​
115 if (count === 3) {
116 return `data${count}`
117 }
118​
119 throw new Error(`error${count}`)
120 },
121 retry: 3,
122 retryDelay: 1,
123 })
124​
125 promise.then((data) => {
126 result = data
127 })
128​
129 // Check if we do not have a result
130 expect(result).toBeUndefined()
131​
132 // Check if the query is really paused
133 await vi.advanceTimersByTimeAsync(1)
134 expect(result).toBeUndefined()
135​
136 // Reset navigator to original value
137 onlineMock.mockReturnValue(true)
138 // trigger online event
139 queryClient.getQueryCache().onOnline()
140​
141 // There should not be a result yet
142 expect(result).toBeUndefined()
143​
144 // Promise should eventually be resolved
145 await vi.advanceTimersByTimeAsync(2)
146 expect(result).toBe('data3')
147 onlineMock.mockRestore()
148 })
149​
150 it('should throw a CancelledError when a paused query is cancelled', async () => {
151 const key = queryKey()
152​
153 // make page unfocused
154 const visibilityMock = mockVisibilityState('hidden')
155​
156 let count = 0
157 let result: unknown
158​
159 const promise = queryClient.fetchQuery({
160 queryKey: key,
161 queryFn: (): Promise<unknown> => {
162 count++
163 throw new Error(`error${count}`)
164 },
165 retry: 3,
166 retryDelay: 1,
167 })
168​
169 promise.catch((data) => {
170 result = data
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(result).toBeUndefined()
178​
179 // Cancel query
180 query.cancel()
181​
182 // Check if the error is set to the cancelled error
183 try {
184 await promise
185 expect.unreachable()
186 } catch {
187 expect(isCancelledError(result)).toBe(true)
188 expect(result instanceof Error).toBe(true)
189 } finally {
190 // Reset visibilityState to original value
191 visibilityMock.mockRestore()
192 }
193 })
194​
195 test('should provide context to queryFn', () => {
196 const key = queryKey()
197​
198 const queryFn = vi
199 .fn<
200 (
201 context: QueryFunctionContext<ReturnType<typeof queryKey>>,
202 ) => Promise<'data'>
203 >()
204 .mockResolvedValue('data')
205​
206 queryClient.prefetchQuery({ queryKey: key, queryFn })
207​
208 expect(queryFn).toHaveBeenCalledTimes(1)
209 const args = queryFn.mock.calls[0]![0]
210 expect(args).toBeDefined()
211 expect(args.pageParam).toBeUndefined()
212 expect(args.queryKey).toEqual(key)
213 expect(args.signal).toBeInstanceOf(AbortSignal)
214 expect(args.client).toEqual(queryClient)
215 })
216​
217 test('should continue if cancellation is not supported and signal is not consumed', async () => {
218 const key = queryKey()
219​
220 queryClient.prefetchQuery({
221 queryKey: key,
222 queryFn: () => sleep(100).then(() => 'data'),
223 })
224​
225 await vi.advanceTimersByTimeAsync(10)
226​
227 // Subscribe and unsubscribe to simulate cancellation because the last observer unsubscribed
228 const observer = new QueryObserver(queryClient, {
229 queryKey: key,
230 enabled: false,
231 })
232 const unsubscribe = observer.subscribe(() => undefined)
233 unsubscribe()
234​
235 await vi.advanceTimersByTimeAsync(90)
236​
237 const query = queryCache.find({ queryKey: key })!
238​
239 expect(query.state).toMatchObject({
240 data: 'data',
241 status: 'success',
242 dataUpdateCount: 1,
243 })
244 })
245​
246 test('should not continue when last observer unsubscribed if the signal was consumed', async () => {
247 const key = queryKey()
248​
249 queryClient.prefetchQuery({
250 queryKey: key,
251 queryFn: async ({ signal }) => {
252 await sleep(100)
253 return signal.aborted ? 'aborted' : 'data'
254 },
255 })
256​
257 await vi.advanceTimersByTimeAsync(10)
258​
259 // Subscribe and unsubscribe to simulate cancellation because the last observer unsubscribed
260 const observer = new QueryObserver(queryClient, {
261 queryKey: key,
262 enabled: false,
263 })
264 const unsubscribe = observer.subscribe(() => undefined)
265 unsubscribe()
266​
267 await vi.advanceTimersByTimeAsync(90)
268​
269 const query = queryCache.find({ queryKey: key })!
270​
271 expect(query.state).toMatchObject({
272 data: undefined,
273 status: 'pending',
274 fetchStatus: 'idle',
275 })
276 })
277​
278 test('should provide an AbortSignal to the queryFn that provides info about the cancellation state', async () => {
279 const key = queryKey()
280​
281 const queryFn =
282 vi.fn<
283 (
284 context: QueryFunctionContext<ReturnType<typeof queryKey>>,
285 ) => Promise<unknown>
286 >()
287 const onAbort = vi.fn()
288 const abortListener = vi.fn()
289 let error
290​
291 queryFn.mockImplementation(async ({ signal }) => {
292 signal.onabort = onAbort
293 signal.addEventListener('abort', abortListener)
294 await sleep(10)
295 signal.onabort = null
296 signal.removeEventListener('abort', abortListener)
297 throw new Error()
298 })
299​
300 const promise = queryClient.fetchQuery({
301 queryKey: key,
302 queryFn,
303 retry: 3,
304 retryDelay: 10,
305 })
306​
307 promise.catch((e) => {
308 error = e
309 })
310​
311 const query = queryCache.find({ queryKey: key })!
312​
313 expect(queryFn).toHaveBeenCalledTimes(1)
314​
315 const signal = queryFn.mock.calls[0]![0].signal
316 expect(signal.aborted).toBe(false)
317 expect(onAbort).not.toHaveBeenCalled()
318 expect(abortListener).not.toHaveBeenCalled()
319​
320 query.cancel()
321​
322 await vi.advanceTimersByTimeAsync(100)
323​
324 expect(signal.aborted).toBe(true)
325 expect(onAbort).toHaveBeenCalledTimes(1)
326 expect(abortListener).toHaveBeenCalledTimes(1)
327 expect(isCancelledError(error)).toBe(true)
328 })
329​
330 test('should not continue if explicitly cancelled', async () => {
331 const key = queryKey()
332​
333 const queryFn = vi.fn<(...args: Array<unknown>) => unknown>()
334​
335 queryFn.mockImplementation(async () => {
336 await sleep(10)
337 throw new Error()
338 })
339​
340 let error
341​
342 const promise = queryClient.fetchQuery({
343 queryKey: key,
344 queryFn,
345 retry: 3,
346 retryDelay: 10,
347 })
348​
349 promise.catch((e) => {
350 error = e
351 })
352​
353 const query = queryCache.find({ queryKey: key })!
354 query.cancel()
355​
356 await vi.advanceTimersByTimeAsync(100)
357​
358 expect(queryFn).toHaveBeenCalledTimes(1)
359 expect(isCancelledError(error)).toBe(true)
360 })
361​
362 test('should not error if reset while pending', async () => {
363 const key = queryKey()
364​
365 const queryFn = vi.fn<(...args: Array<unknown>) => unknown>()
366​
367 queryFn.mockImplementation(async () => {
368 await sleep(10)
369 throw new Error()
370 })
371​
372 queryClient.fetchQuery({ queryKey: key, queryFn, retry: 3, retryDelay: 10 })
373​
374 // Ensure the query is pending
375 const query = queryCache.find({ queryKey: key })!
376 expect(query.state.status).toBe('pending')
377​
378 // Reset the query while it is pending
379 query.reset()
380​
381 await vi.advanceTimersByTimeAsync(100)
382​
383 // The query should
384 expect(queryFn).toHaveBeenCalledTimes(1) // have been called,
385 expect(query.state.error).toBe(null) // not have an error, and
386 expect(query.state.fetchStatus).toBe('idle') // not be loading any longer
387 })
388​
389 test('should reset to default state when created from hydration', async () => {
390 const client = createQueryClient()
391 await client.prefetchQuery({
392 queryKey: ['string'],
393 queryFn: () => Promise.resolve('string'),
394 })
395​
396 const dehydrated = dehydrate(client)
397​
398 const hydrationClient = createQueryClient()
399 hydrate(hydrationClient, dehydrated)
400​
401 expect(hydrationClient.getQueryData(['string'])).toBe('string')
402​
403 const query = hydrationClient.getQueryCache().find({ queryKey: ['string'] })
404 query?.reset()
405​
406 expect(hydrationClient.getQueryData(['string'])).toBe(undefined)
407 })
408​
409 test('should be able to refetch a cancelled query', async () => {
410 const key = queryKey()
411​
412 const queryFn = vi.fn<(...args: Array<unknown>) => unknown>()
413​
414 queryFn.mockImplementation(() => sleep(50).then(() => 'data'))
415​
416 queryClient.prefetchQuery({ queryKey: key, queryFn })
417 const query = queryCache.find({ queryKey: key })!
418 await vi.advanceTimersByTimeAsync(10)
419 query.cancel()
420 await vi.advanceTimersByTimeAsync(100)
421​
422 expect(queryFn).toHaveBeenCalledTimes(1)
423 expect(isCancelledError(query.state.error)).toBe(true)
424 const result = query.fetch()
425 await vi.advanceTimersByTimeAsync(50)
426 await expect(result).resolves.toBe('data')
427 expect(query.state.error).toBe(null)
428 expect(queryFn).toHaveBeenCalledTimes(2)
429 })
430​
431 test('cancelling a resolved query should not have any effect', async () => {
432 const key = queryKey()
433 await queryClient.prefetchQuery({
434 queryKey: key,
435 queryFn: () => 'data',
436 })
437 const query = queryCache.find({ queryKey: key })!
438 query.cancel()
439 await vi.advanceTimersByTimeAsync(10)
440 expect(query.state.data).toBe('data')
441 })
442​
443 test('cancelling a rejected query should not have any effect', async () => {
444 const key = queryKey()
445 const error = new Error('error')
446​
447 await queryClient.prefetchQuery({
448 queryKey: key,
449 queryFn: () => Promise.reject(error),
450 })
451 const query = queryCache.find({ queryKey: key })!
452 query.cancel()
453 await vi.advanceTimersByTimeAsync(10)
454​
455 expect(query.state.error).toBe(error)
456 expect(isCancelledError(query.state.error)).toBe(false)
457 })
458​
459 test('the previous query status should be kept when refetching', async () => {
460 const key = queryKey()
461​
462 await queryClient.prefetchQuery({ queryKey: key, queryFn: () => 'data' })
463 const query = queryCache.find({ queryKey: key })!
464 expect(query.state.status).toBe('success')
465​
466 await queryClient.prefetchQuery({
467 queryKey: key,
468 queryFn: () => Promise.reject<string>('reject'),
469 retry: false,
470 })
471 expect(query.state.status).toBe('error')
472​
473 queryClient.prefetchQuery({
474 queryKey: key,
475 queryFn: () => sleep(10).then(() => Promise.reject<unknown>('reject')),
476 retry: false,
477 })
478 expect(query.state.status).toBe('error')
479​
480 await vi.advanceTimersByTimeAsync(10)
481 expect(query.state.status).toBe('error')
482 })
483​
484 test('queries with gcTime 0 should be removed immediately after unsubscribing', async () => {
485 const key = queryKey()
486 let count = 0
487 const observer = new QueryObserver(queryClient, {
488 queryKey: key,
489 queryFn: () => {
490 count++
491 return 'data'
492 },
493 gcTime: 0,
494 staleTime: Infinity,
495 })
496 const unsubscribe1 = observer.subscribe(() => undefined)
497 unsubscribe1()
498 await vi.waitFor(() =>
499 expect(queryCache.find({ queryKey: key })).toBeUndefined(),
500 )
501 const unsubscribe2 = observer.subscribe(() => undefined)
502 unsubscribe2()
503​
504 await vi.waitFor(() =>
505 expect(queryCache.find({ queryKey: key })).toBeUndefined(),
506 )
507 expect(count).toBe(1)
508 })
509​
510 test('should be garbage collected when unsubscribed to', async () => {
511 const key = queryKey()
512 const observer = new QueryObserver(queryClient, {
513 queryKey: key,
514 queryFn: () => 'data',
515 gcTime: 0,
516 })
517 expect(queryCache.find({ queryKey: key })).toBeDefined()
518 const unsubscribe = observer.subscribe(() => undefined)
519 expect(queryCache.find({ queryKey: key })).toBeDefined()
520 unsubscribe()
521 await vi.waitFor(() =>
522 expect(queryCache.find({ queryKey: key })).toBeUndefined(),
523 )
524 })
525​
526 test('should be garbage collected later when unsubscribed and query is fetching', async () => {
527 const key = queryKey()
528 const observer = new QueryObserver(queryClient, {
529 queryKey: key,
530 queryFn: () => sleep(20).then(() => 'data'),
531 gcTime: 10,
532 })
533 const unsubscribe = observer.subscribe(() => undefined)
534 await vi.advanceTimersByTimeAsync(20)
535 expect(queryCache.find({ queryKey: key })).toBeDefined()
536 observer.refetch()
537 unsubscribe()
538 // unsubscribe should not remove even though gcTime has elapsed b/c query is still fetching
539 expect(queryCache.find({ queryKey: key })).toBeDefined()
540 // should be removed after an additional staleTime wait
541 await vi.waitFor(() =>
542 expect(queryCache.find({ queryKey: key })).toBeUndefined(),
543 )
544 })
545​
546 test('should not be garbage collected unless there are no subscribers', async () => {
547 const key = queryKey()
548 const observer = new QueryObserver(queryClient, {
549 queryKey: key,
550 queryFn: () => 'data',
551 gcTime: 0,
552 })
553 expect(queryCache.find({ queryKey: key })).toBeDefined()
554 const unsubscribe = observer.subscribe(() => undefined)
555 await vi.advanceTimersByTimeAsync(100)
556 expect(queryCache.find({ queryKey: key })).toBeDefined()
557 unsubscribe()
558 await vi.advanceTimersByTimeAsync(100)
559 expect(queryCache.find({ queryKey: key })).toBeUndefined()
560 queryClient.setQueryData(key, 'data')
561 await vi.advanceTimersByTimeAsync(100)
562 expect(queryCache.find({ queryKey: key })).toBeDefined()
563 })
564​
565 test('should return proper count of observers', () => {
566 const key = queryKey()
567 const options = { queryKey: key, queryFn: () => 'data' }
568 const observer = new QueryObserver(queryClient, options)
569 const observer2 = new QueryObserver(queryClient, options)
570 const observer3 = new QueryObserver(queryClient, options)
571 const query = queryCache.find({ queryKey: key })
572​
573 expect(query?.getObserversCount()).toEqual(0)
574​
575 const unsubscribe1 = observer.subscribe(() => undefined)
576 const unsubscribe2 = observer2.subscribe(() => undefined)
577 const unsubscribe3 = observer3.subscribe(() => undefined)
578 expect(query?.getObserversCount()).toEqual(3)
579​
580 unsubscribe3()
581 expect(query?.getObserversCount()).toEqual(2)
582​
583 unsubscribe2()
584 expect(query?.getObserversCount()).toEqual(1)
585​
586 unsubscribe1()
587 expect(query?.getObserversCount()).toEqual(0)
588 })
589​
590 test('stores meta object in query', async () => {
591 const meta = {
592 it: 'works',
593 }
594​
595 const key = queryKey()
596​
597 await queryClient.prefetchQuery({
598 queryKey: key,
599 queryFn: () => 'data',
600 meta,
601 })
602​
603 const query = queryCache.find({ queryKey: key })!
604​
605 expect(query.meta).toBe(meta)
606 expect(query.options.meta).toBe(meta)
607 })
608​
609 test('updates meta object on change', async () => {
610 const meta = {
611 it: 'works',
612 }
613​
614 const key = queryKey()
615 const queryFn = () => 'data'
616​
617 await queryClient.prefetchQuery({ queryKey: key, queryFn, meta })
618​
619 await queryClient.prefetchQuery({ queryKey: key, queryFn, meta: undefined })
620​
621 const query = queryCache.find({ queryKey: key })!
622​
623 expect(query.meta).toBeUndefined()
624 expect(query.options.meta).toBeUndefined()
625 })
626​
627 test('can use default meta', async () => {
628 const meta = {
629 it: 'works',
630 }
631​
632 const key = queryKey()
633 const queryFn = () => 'data'
634​
635 queryClient.setQueryDefaults(key, { meta })
636​
637 await queryClient.prefetchQuery({ queryKey: key, queryFn })
638​
639 const query = queryCache.find({ queryKey: key })!
640​
641 expect(query.meta).toBe(meta)
642 })
643​
644 test('provides meta object inside query function', async () => {
645 const meta = {
646 it: 'works',
647 }
648​
649 const queryFn = vi.fn(() => 'data')
650​
651 const key = queryKey()
652​
653 await queryClient.prefetchQuery({ queryKey: key, queryFn, meta })
654​
655 expect(queryFn).toBeCalledWith(
656 expect.objectContaining({
657 meta,
658 }),
659 )
660 })
661​
662 test('should refetch the observer when online method is called', () => {
663 const key = queryKey()
664​
665 const observer = new QueryObserver(queryClient, {
666 queryKey: key,
667 queryFn: () => 'data',
668 })
669​
670 const refetchSpy = vi.spyOn(observer, 'refetch')
671 const unsubscribe = observer.subscribe(() => undefined)
672 queryCache.onOnline()
673​
674 // Should refetch the observer
675 expect(refetchSpy).toHaveBeenCalledTimes(1)
676​
677 unsubscribe()
678 refetchSpy.mockRestore()
679 })
680​
681 test('should not add an existing observer', async () => {
682 const key = queryKey()
683​
684 await queryClient.prefetchQuery({ queryKey: key, queryFn: () => 'data' })
685 const query = queryCache.find({ queryKey: key })!
686 expect(query.getObserversCount()).toEqual(0)
687​
688 const observer = new QueryObserver(queryClient, {
689 queryKey: key,
690 })
691 expect(query.getObserversCount()).toEqual(0)
692​
693 query.addObserver(observer)
694 expect(query.getObserversCount()).toEqual(1)
695​
696 query.addObserver(observer)
697 expect(query.getObserversCount()).toEqual(1)
698 })
699​
700 test('should not try to remove an observer that does not exist', async () => {
701 const key = queryKey()
702​
703 await queryClient.prefetchQuery({ queryKey: key, queryFn: () => 'data' })
704 const query = queryCache.find({ queryKey: key })!
705 const observer = new QueryObserver(queryClient, {
706 queryKey: key,
707 })
708 expect(query.getObserversCount()).toEqual(0)
709​
710 const notifySpy = vi.spyOn(queryCache, 'notify')
711 expect(() => query.removeObserver(observer)).not.toThrow()
712 expect(notifySpy).not.toHaveBeenCalled()
713​
714 notifySpy.mockRestore()
715 })
716​
717 test('should not change state on invalidate() if already invalidated', async () => {
718 const key = queryKey()
719​
720 await queryClient.prefetchQuery({ queryKey: key, queryFn: () => 'data' })
721 const query = queryCache.find({ queryKey: key })!
722​
723 query.invalidate()
724 expect(query.state.isInvalidated).toBeTruthy()
725​
726 const previousState = query.state
727​
728 query.invalidate()
729​
730 expect(query.state).toBe(previousState)
731 })
732​
733 test('fetch should not dispatch "fetch" query is already fetching', async () => {
734 const key = queryKey()
735​
736 const queryFn = () => sleep(10).then(() => 'data')
737​
738 const updates: Array<string> = []
739​
740 queryClient.prefetchQuery({ queryKey: key, queryFn })
741 await vi.advanceTimersByTimeAsync(10)
742 const query = queryCache.find({ queryKey: key })!
743​
744 const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
745 updates.push(event.type)
746 })
747​
748 void query.fetch({
749 queryKey: key,
750 queryFn,
751 })
752​
753 query.fetch({
754 queryKey: key,
755 queryFn,
756 })
757 await vi.advanceTimersByTimeAsync(10)
758​
759 expect(updates).toEqual([
760 'updated', // type: 'fetch'
761 'updated', // type: 'success'
762 ]),
763 unsubscribe()
764 })
765​
766 test('fetch should throw an error if the queryFn is not defined', async () => {
767 const key = queryKey()
768​
769 const observer = new QueryObserver(queryClient, {
770 queryKey: key,
771 queryFn: undefined,
772 retry: false,
773 })
774​
775 const unsubscribe = observer.subscribe(() => undefined)
776​
777 await vi.advanceTimersByTimeAsync(10)
778 const query = queryCache.find({ queryKey: key })!
779 expect(observer.getCurrentResult()).toMatchObject({
780 status: 'error',
781 error: new Error(`Missing queryFn: '${query.queryHash}'`),
782 })
783 unsubscribe()
784 })
785​
786 test('fetch should dispatch an error if the queryFn returns undefined', async () => {
787 const consoleMock = vi.spyOn(console, 'error')
788 consoleMock.mockImplementation(() => undefined)
789 const key = queryKey()
790​
791 const observer = new QueryObserver(queryClient, {
792 queryKey: key,
793 queryFn: () => undefined,
794 retry: false,
795 })
796​
797 let observerResult: QueryObserverResult<unknown, unknown> | undefined
798​
799 const unsubscribe = observer.subscribe((result) => {
800 observerResult = result
801 })
802​
803 await vi.advanceTimersByTimeAsync(10)
804​
805 const error = new Error(`${JSON.stringify(key)} data is undefined`)
806​
807 expect(observerResult).toMatchObject({
808 isError: true,
809 error,
810 })
811​
812 expect(consoleMock).toHaveBeenCalledWith(
813 `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ["${key}"]`,
814 )
815 unsubscribe()
816 consoleMock.mockRestore()
817 })
818​
819 it('should not retry on the server', async () => {
820 const resetIsServer = setIsServer(true)
821​
822 const key = queryKey()
823 let count = 0
824​
825 const observer = new QueryObserver(queryClient, {
826 queryKey: key,
827 queryFn: () => {
828 count++
829 return Promise.reject(new Error('error'))
830 },
831 })
832​
833 await observer.refetch()
834​
835 expect(count).toBe(1)
836​
837 resetIsServer()
838 })
839​
840 test('constructor should call initialDataUpdatedAt if defined as a function', async () => {
841 const key = queryKey()
842​
843 const initialDataUpdatedAtSpy = vi.fn()
844​
845 await queryClient.prefetchQuery({
846 queryKey: key,
847 queryFn: () => 'data',
848 initialData: 'initial',
849 initialDataUpdatedAt: initialDataUpdatedAtSpy,
850 })
851​
852 expect(initialDataUpdatedAtSpy).toHaveBeenCalled()
853 })
854​
855 test('should work with initialDataUpdatedAt set to zero', async () => {
856 const key = queryKey()
857​
858 await queryClient.prefetchQuery({
859 queryKey: key,
860 queryFn: () => 'data',
861 staleTime: Infinity,
862 initialData: 'initial',
863 initialDataUpdatedAt: 0,
864 })
865​
866 expect(queryCache.find({ queryKey: key })?.state).toMatchObject({
867 data: 'initial',
868 status: 'success',
869 dataUpdatedAt: 0,
870 })
871 })
872​
873 test('queries should be garbage collected even if they never fetched', async () => {
874 const key = queryKey()
875​
876 queryClient.setQueryDefaults(key, { gcTime: 10 })
877​
878 const fn = vi.fn()
879​
880 const unsubscribe = queryClient.getQueryCache().subscribe(fn)
881​
882 queryClient.setQueryData(key, 'data')
883​
884 await vi.waitFor(() =>
885 expect(fn).toHaveBeenCalledWith(
886 expect.objectContaining({
887 type: 'removed',
888 }),
889 ),
890 )
891​
892 expect(queryClient.getQueryCache().findAll()).toHaveLength(0)
893​
894 unsubscribe()
895 })
896​
897 test('should always revert to idle state (#5958)', async () => {
898 let mockedData = [1]
899​
900 const key = queryKey()
901​
902 const queryFn = vi
903 .fn<
904 (
905 context: QueryFunctionContext<ReturnType<typeof queryKey>>,
906 ) => Promise<unknown>
907 >()
908 .mockImplementation(
909 ({ signal }) =>
910 new Promise((resolve, reject) => {
911 const abortListener = () => {
912 clearTimeout(timerId)
913 reject(signal.reason)
914 }
915 signal.addEventListener('abort', abortListener)
916​
917 const timerId = setTimeout(() => {
918 signal.removeEventListener('abort', abortListener)
919 resolve(mockedData.join(' - '))
920 }, 50)
921 }),
922 )
923​
924 const observer = new QueryObserver(queryClient, {
925 queryKey: key,
926 queryFn,
927 })
928 const unsubscribe = observer.subscribe(() => undefined)
929 await vi.advanceTimersByTimeAsync(50) // let it resolve
930​
931 mockedData = [1, 2] // update "server" state in the background
932​
933 queryClient.invalidateQueries({ queryKey: key })
934 queryClient.invalidateQueries({ queryKey: key })
935 unsubscribe() // unsubscribe to simulate unmount
936​
937 // set up a new observer to simulate a mount of new component
938 const newObserver = new QueryObserver(queryClient, {
939 queryKey: key,
940 queryFn,
941 })
942​
943 const spy = vi.fn()
944 newObserver.subscribe(({ data }) => spy(data))
945 await vi.advanceTimersByTimeAsync(60) // let it resolve
946 expect(spy).toHaveBeenCalledWith('1 - 2')
947 })
948​
949 it('should have an error log when queryFn data is not serializable', async () => {
950 const consoleMock = vi.spyOn(console, 'error')
951​
952 consoleMock.mockImplementation(() => undefined)
953​
954 const key = queryKey()
955​
956 const queryFn = vi.fn()
957​
958 const data: Array<{
959 id: number
960 name: string
961 link: null | { id: number; name: string; link: unknown }
962 }> = Array.from({ length: 5 })
963 .fill(null)
964 .map((_, index) => ({
965 id: index,
966 name: `name-${index}`,
967 link: null,
968 }))
969​
970 if (data[0] && data[1]) {
971 data[0].link = data[1]
972 data[1].link = data[0]
973 }
974​
975 queryFn.mockImplementation(() => sleep(10).then(() => data))
976​
977 queryClient.prefetchQuery({
978 queryKey: key,
979 queryFn,
980 initialData: structuredClone(data),
981 })
982 await vi.advanceTimersByTimeAsync(10)
983​
984 const query = queryCache.find({ queryKey: key })!
985​
986 expect(queryFn).toHaveBeenCalledTimes(1)
987​
988 expect(query.state.status).toBe('error')
989 expect(
990 query.state.error?.message.includes('Maximum call stack size exceeded'),
991 ).toBeTruthy()
992​
993 expect(consoleMock).toHaveBeenCalledWith(
994 expect.stringContaining(
995 'Structural sharing requires data to be JSON serializable',
996 ),
997 )
998​
999 consoleMock.mockRestore()
1000 })
1001​
1002 it('should have an error status when setData has any error inside', async () => {
1003 const key = queryKey()
1004​
1005 const queryFn = vi
1006 .fn()
1007 .mockImplementation(() => sleep(10).then(() => 'data'))
1008​
1009 queryClient.prefetchQuery({
1010 queryKey: key,
1011 queryFn,
1012 structuralSharing: () => {
1013 throw Error('Any error')
1014 },
1015 })
1016​
1017 const query = queryCache.find({ queryKey: key })!
1018​
1019 expect(queryFn).toHaveBeenCalledTimes(1)
1020 await vi.advanceTimersByTimeAsync(10)
1021 expect(query.state.status).toBe('error')
1022 })