Open History to see the last commit
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 })
1023})