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

query.test.tsx

1,447 lines38.9 KB

1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2import {
3 mockVisibilityState,
4 queryKey,
5 sleep,
6} from '@tanstack/query-test-utils'
7import {
8 CancelledError,
9 Query,
10 QueryCache,
11 QueryClient,
12 QueryObserver,
13 dehydrate,
14 hydrate,
15 noop,
16} from '..'
17import { hashQueryKeyByOptions } from '../utils'
18import { mockOnlineManagerIsOnline, setIsServer } from './utils'
19import type { QueryFunctionContext, QueryKey, QueryObserverResult } from '..'
20​
21describe('query', () => {
22 let queryClient: QueryClient
23 let queryCache: QueryCache
24​
25 beforeEach(() => {
26 vi.useFakeTimers()
27 queryClient = new QueryClient()
28 queryCache = queryClient.getQueryCache()
29 queryClient.mount()
30 })
31​
32 afterEach(() => {
33 queryClient.clear()
34 vi.useRealTimers()
35 })
36​
37 it('should use the longest garbage collection time it has seen', async () => {
38 const key = queryKey()
39 await queryClient
40 .query({
41 queryKey: key,
42 queryFn: () => 'data',
43 gcTime: 100,
44 })
45 .catch(noop)
46 await queryClient
47 .query({
48 queryKey: key,
49 queryFn: () => 'data',
50 gcTime: 200,
51 })
52 .catch(noop)
53 await queryClient
54 .query({
55 queryKey: key,
56 queryFn: () => 'data',
57 gcTime: 10,
58 })
59 .catch(noop)
60 const query = queryCache.find({ queryKey: key })!
61 expect(query.gcTime).toBe(200)
62 })
63​
64 it('should continue retry after focus regain and resolve all promises', async () => {
65 const key = queryKey()
66​
67 // make page unfocused
68 const visibilityMock = mockVisibilityState('hidden')
69​
70 let count = 0
71 let result
72​
73 const promise = queryClient.query({
74 queryKey: key,
75 queryFn: () => {
76 count++
77​
78 if (count === 3) {
79 return `data${count}`
80 }
81​
82 throw new Error(`error${count}`)
83 },
84 retry: 3,
85 retryDelay: 1,
86 })
87​
88 promise.then((data) => {
89 result = data
90 })
91​
92 // Check if we do not have a result
93 expect(result).toBeUndefined()
94​
95 // Check if the query is really paused
96 await vi.advanceTimersByTimeAsync(50)
97 expect(result).toBeUndefined()
98​
99 // Reset visibilityState to original value
100 visibilityMock.mockRestore()
101 window.dispatchEvent(new Event('visibilitychange'))
102​
103 // There should not be a result yet
104 expect(result).toBeUndefined()
105​
106 // By now we should have a value
107 await vi.advanceTimersByTimeAsync(50)
108 expect(result).toBe('data3')
109 })
110​
111 it('should continue retry after reconnect and resolve all promises', async () => {
112 const key = queryKey()
113​
114 const onlineMock = mockOnlineManagerIsOnline(false)
115​
116 let count = 0
117 let result
118​
119 const promise = queryClient.query({
120 queryKey: key,
121 queryFn: () => {
122 count++
123​
124 if (count === 3) {
125 return `data${count}`
126 }
127​
128 throw new Error(`error${count}`)
129 },
130 retry: 3,
131 retryDelay: 1,
132 })
133​
134 promise.then((data) => {
135 result = data
136 })
137​
138 // Check if we do not have a result
139 expect(result).toBeUndefined()
140​
141 // Check if the query is really paused
142 await vi.advanceTimersByTimeAsync(1)
143 expect(result).toBeUndefined()
144​
145 // Reset navigator to original value
146 onlineMock.mockReturnValue(true)
147 // trigger online event
148 queryClient.getQueryCache().onOnline()
149​
150 // There should not be a result yet
151 expect(result).toBeUndefined()
152​
153 // Promise should eventually be resolved
154 await vi.advanceTimersByTimeAsync(2)
155 expect(result).toBe('data3')
156 onlineMock.mockRestore()
157 })
158​
159 it('should throw a CancelledError when a paused query is cancelled', async () => {
160 const key = queryKey()
161​
162 // make page unfocused
163 const visibilityMock = mockVisibilityState('hidden')
164 let count = 0
165​
166 const promise = queryClient.query({
167 queryKey: key,
168 queryFn: (): Promise<unknown> => {
169 count++
170 throw new Error(`error${count}`)
171 },
172 retry: 3,
173 retryDelay: 1,
174 })
175​
176 const query = queryCache.find({ queryKey: key })!
177​
178 // Check if the query is really paused
179 await vi.advanceTimersByTimeAsync(50)
180 expect(query.state.fetchStatus).toBe('paused')
181​
182 // Cancel query
183 query.cancel()
184​
185 // Check if the error is set to the cancelled error
186 try {
187 await expect(promise).rejects.toBeInstanceOf(CancelledError)
188 } finally {
189 // Reset visibilityState to original value
190 visibilityMock.mockRestore()
191 }
192 })
193​
194 it('should cancel a paused initial fetch when the last observer unsubscribes', async () => {
195 const key = queryKey()
196 const onlineMock = mockOnlineManagerIsOnline(false)
197 let count = 0
198​
199 const observer = new QueryObserver(queryClient, {
200 queryKey: key,
201 queryFn: async ({ signal: _signal }) => {
202 count++
203 await sleep(10)
204 return `data${count}`
205 },
206 })
207​
208 const unsubscribe = observer.subscribe(() => undefined)
209 const query = queryCache.find({ queryKey: key })!
210​
211 expect(query.state).toMatchObject({
212 fetchStatus: 'paused',
213 status: 'pending',
214 })
215​
216 unsubscribe()
217 expect(query.state).toMatchObject({
218 fetchStatus: 'idle',
219 status: 'pending',
220 })
221​
222 onlineMock.mockReturnValue(true)
223 queryClient.getQueryCache().onOnline()
224​
225 await vi.advanceTimersByTimeAsync(11)
226 expect(query.state).toMatchObject({
227 fetchStatus: 'idle',
228 status: 'pending',
229 })
230 expect(count).toBe(0)
231​
232 onlineMock.mockRestore()
233 })
234​
235 it('should not throw a CancelledError when fetchQuery is in progress and the last observer unsubscribes when AbortSignal is consumed', async () => {
236 const key = queryKey()
237​
238 const observer = new QueryObserver(queryClient, {
239 queryKey: key,
240 queryFn: () => sleep(100).then(() => 'data'),
241 })
242​
243 const unsubscribe = observer.subscribe(() => undefined)
244 await vi.advanceTimersByTimeAsync(100)
245 expect(queryCache.find({ queryKey: key })?.state.data).toBe('data')
246​
247 const promise = queryClient.query({
248 queryKey: key,
249 queryFn: ({ signal }) => sleep(100).then(() => 'data2' + String(signal)),
250 })
251​
252 // Ensure the fetch is in progress
253 await vi.advanceTimersByTimeAsync(10)
254​
255 // Unsubscribe while fetch is in progress
256 unsubscribe()
257 // await queryClient.cancelQueries()
258​
259 await vi.advanceTimersByTimeAsync(90)
260​
261 // Fetch should complete successfully without throwing a CancelledError
262 await expect(promise).resolves.toBe('data')
263​
264 expect(queryCache.find({ queryKey: key })?.state.data).toBe('data')
265 })
266​
267 it('should provide context to queryFn', () => {
268 const key = queryKey()
269​
270 const queryFn = vi
271 .fn<
272 (
273 context: QueryFunctionContext<ReturnType<typeof queryKey>>,
274 ) => Promise<'data'>
275 >()
276 .mockResolvedValue('data')
277​
278 void queryClient.query({ queryKey: key, queryFn }).catch(noop)
279 expect(queryFn).toHaveBeenCalledTimes(1)
280 const args = queryFn.mock.calls[0]![0]
281 expect(args.pageParam).toBeUndefined()
282 expect(args.queryKey).toEqual(key)
283 expect(args.signal).toBeInstanceOf(AbortSignal)
284 expect(args.client).toEqual(queryClient)
285 })
286​
287 it('should continue if cancellation is not supported and signal is not consumed', async () => {
288 const key = queryKey()
289​
290 void queryClient
291 .query({
292 queryKey: key,
293 queryFn: () => sleep(100).then(() => 'data'),
294 })
295 .catch(noop)
296 await vi.advanceTimersByTimeAsync(10)
297​
298 // Subscribe and unsubscribe to simulate cancellation because the last observer unsubscribed
299 const observer = new QueryObserver(queryClient, {
300 queryKey: key,
301 enabled: false,
302 })
303 const unsubscribe = observer.subscribe(() => undefined)
304 unsubscribe()
305 await vi.advanceTimersByTimeAsync(90)
306​
307 const query = queryCache.find({ queryKey: key })!
308​
309 expect(query.state).toMatchObject({
310 data: 'data',
311 status: 'success',
312 dataUpdateCount: 1,
313 })
314 })
315​
316 it('should not continue when last observer unsubscribed if the signal was consumed', async () => {
317 const key = queryKey()
318​
319 void queryClient
320 .query({
321 queryKey: key,
322 queryFn: ({ signal }) =>
323 sleep(100).then(() => (signal.aborted ? 'aborted' : 'data')),
324 })
325 .catch(noop)
326 await vi.advanceTimersByTimeAsync(10)
327​
328 // Subscribe and unsubscribe to simulate cancellation because the last observer unsubscribed
329 const observer = new QueryObserver(queryClient, {
330 queryKey: key,
331 enabled: false,
332 })
333 const unsubscribe = observer.subscribe(() => undefined)
334 unsubscribe()
335 await vi.advanceTimersByTimeAsync(90)
336​
337 const query = queryCache.find({ queryKey: key })!
338​
339 expect(query.state).toMatchObject({
340 data: undefined,
341 status: 'pending',
342 fetchStatus: 'idle',
343 })
344 })
345​
346 it('should provide an AbortSignal to the queryFn that provides info about the cancellation state', async () => {
347 const key = queryKey()
348​
349 const queryFn =
350 vi.fn<
351 (
352 context: QueryFunctionContext<ReturnType<typeof queryKey>>,
353 ) => Promise<unknown>
354 >()
355 const onAbort = vi.fn()
356 const abortListener = vi.fn()
357 let error
358​
359 queryFn.mockImplementation(async ({ signal }) => {
360 signal.onabort = onAbort
361 signal.addEventListener('abort', abortListener)
362 await sleep(10)
363 signal.onabort = null
364 signal.removeEventListener('abort', abortListener)
365 throw new Error()
366 })
367​
368 const promise = queryClient.query({
369 queryKey: key,
370 queryFn,
371 retry: 3,
372 retryDelay: 10,
373 })
374​
375 promise.catch((e) => {
376 error = e
377 })
378​
379 const query = queryCache.find({ queryKey: key })!
380​
381 expect(queryFn).toHaveBeenCalledTimes(1)
382​
383 const signal = queryFn.mock.calls[0]![0].signal
384 expect(signal.aborted).toBe(false)
385 expect(onAbort).not.toHaveBeenCalled()
386 expect(abortListener).not.toHaveBeenCalled()
387​
388 query.cancel()
389 await vi.advanceTimersByTimeAsync(100)
390 expect(signal.aborted).toBe(true)
391 expect(onAbort).toHaveBeenCalledTimes(1)
392 expect(abortListener).toHaveBeenCalledTimes(1)
393 expect(error).toBeInstanceOf(CancelledError)
394 })
395​
396 it('should not continue if explicitly cancelled', async () => {
397 const key = queryKey()
398​
399 const queryFn = vi.fn<(...args: Array<unknown>) => unknown>()
400​
401 queryFn.mockImplementation(async () => {
402 await sleep(10)
403 throw new Error()
404 })
405​
406 let error
407​
408 const promise = queryClient.query({
409 queryKey: key,
410 queryFn,
411 retry: 3,
412 retryDelay: 10,
413 })
414​
415 promise.catch((e) => {
416 error = e
417 })
418​
419 const query = queryCache.find({ queryKey: key })!
420 query.cancel()
421 await vi.advanceTimersByTimeAsync(100)
422 expect(queryFn).toHaveBeenCalledTimes(1)
423 expect(error).toBeInstanceOf(CancelledError)
424 })
425​
426 it('should not error if reset while pending', async () => {
427 const key = queryKey()
428​
429 const queryFn = vi.fn<(...args: Array<unknown>) => unknown>()
430​
431 queryFn.mockImplementation(async () => {
432 await sleep(10)
433 throw new Error()
434 })
435​
436 let error
437​
438 queryClient
439 .query({
440 queryKey: key,
441 queryFn,
442 retry: 3,
443 retryDelay: 10,
444 })
445 .catch((e) => {
446 error = e
447 })
448​
449 // Ensure the query is pending
450 const query = queryCache.find({ queryKey: key })!
451 expect(query.state.status).toBe('pending')
452​
453 // Reset the query while it is pending
454 query.reset()
455 await vi.advanceTimersByTimeAsync(100)
456​
457 // The query should
458 expect(queryFn).toHaveBeenCalledTimes(1) // have been called,
459 expect(query.state.error).toBe(null) // not have an error, and
460 expect(query.state.fetchStatus).toBe('idle') // not be loading any longer
461 expect(query.state.data).toBe(undefined) // have no data
462​
463 // the call to fetchQuery must reject
464 // because it was reset and not reverted
465 // so it would resolve with undefined otherwise
466 expect(error).toBeInstanceOf(CancelledError)
467 })
468​
469 it('should reset to default state when created from hydration', async () => {
470 const key = queryKey()
471 const client = new QueryClient()
472 await client
473 .query({
474 queryKey: key,
475 queryFn: () => Promise.resolve('string'),
476 })
477 .catch(noop)
478​
479 const dehydrated = dehydrate(client)
480​
481 const hydrationClient = new QueryClient()
482 hydrate(hydrationClient, dehydrated)
483 expect(hydrationClient.getQueryData(key)).toBe('string')
484​
485 const query = hydrationClient.getQueryCache().find({ queryKey: key })
486 query?.reset()
487​
488 expect(hydrationClient.getQueryData(key)).toBe(undefined)
489 })
490​
491 it('should be able to refetch a cancelled query', async () => {
492 const key = queryKey()
493​
494 const queryFn = vi.fn<(...args: Array<unknown>) => unknown>()
495​
496 queryFn.mockImplementation(() => sleep(50).then(() => 'data'))
497​
498 void queryClient.query({ queryKey: key, queryFn }).catch(noop)
499 const query = queryCache.find({ queryKey: key })!
500 await vi.advanceTimersByTimeAsync(10)
501 query.cancel()
502 await vi.advanceTimersByTimeAsync(100)
503 expect(queryFn).toHaveBeenCalledTimes(1)
504 expect(query.state.error).toBeInstanceOf(CancelledError)
505​
506 const result = query.fetch()
507 await vi.advanceTimersByTimeAsync(50)
508 await expect(result).resolves.toBe('data')
509 expect(query.state.error).toBe(null)
510 expect(queryFn).toHaveBeenCalledTimes(2)
511 })
512​
513 it('should not have any effect when cancelling a resolved query', async () => {
514 const key = queryKey()
515 await queryClient
516 .query({
517 queryKey: key,
518 queryFn: () => 'data',
519 })
520 .catch(noop)
521 const query = queryCache.find({ queryKey: key })!
522 query.cancel()
523 await vi.advanceTimersByTimeAsync(10)
524 expect(query.state.data).toBe('data')
525 })
526​
527 it('should not have any effect when cancelling a rejected query', async () => {
528 const key = queryKey()
529 const error = new Error('error')
530​
531 await queryClient
532 .query({
533 queryKey: key,
534 queryFn: () => Promise.reject(error),
535 })
536 .catch(noop)
537 const query = queryCache.find({ queryKey: key })!
538 query.cancel()
539 await vi.advanceTimersByTimeAsync(10)
540 expect(query.state.error).toBe(error)
541 expect(query.state.error).not.toBeInstanceOf(CancelledError)
542 })
543​
544 it('should release the retryer once its fetch has settled', async () => {
545 const key = queryKey()
546 let refetch: Promise<unknown> | undefined
547 const testCache = new QueryCache({
548 onSuccess: (_data, query) => {
549 refetch ??= query.fetch()
550 },
551 })
552 const testClient = new QueryClient({ queryCache: testCache })
553​
554 const prefetch = testClient
555 .query({
556 queryKey: key,
557 queryFn: () => sleep(10).then(() => 'data'),
558 })
559 .catch(noop)
560 const query = testCache.find({ queryKey: key })!
561 const firstPromise = query.promise
562 expect(firstPromise).toBeDefined()
563 await vi.advanceTimersByTimeAsync(10)
564 await prefetch
565 expect(query.promise).toBeDefined()
566 expect(query.promise).not.toBe(firstPromise)
567 await vi.advanceTimersByTimeAsync(10)
568 await refetch
569 expect(query.state.data).toBe('data')
570 expect(query.promise).toBeUndefined()
571 })
572​
573 it('should keep the previous query status when refetching', async () => {
574 const key = queryKey()
575​
576 await queryClient
577 .query({ queryKey: key, queryFn: () => 'data' })
578 .catch(noop)
579 const query = queryCache.find({ queryKey: key })!
580 expect(query.state.status).toBe('success')
581​
582 await queryClient
583 .query({
584 queryKey: key,
585 queryFn: () => Promise.reject<string>('reject'),
586 retry: false,
587 })
588 .catch(noop)
589 expect(query.state.status).toBe('error')
590​
591 void queryClient
592 .query({
593 queryKey: key,
594 queryFn: () => sleep(10).then(() => Promise.reject<unknown>('reject')),
595 retry: false,
596 })
597 .catch(noop)
598 expect(query.state.status).toBe('error')
599 await vi.advanceTimersByTimeAsync(10)
600 expect(query.state.status).toBe('error')
601 })
602​
603 it('should remove queries with gcTime 0 immediately after unsubscribing', async () => {
604 const key = queryKey()
605 let count = 0
606 const observer = new QueryObserver(queryClient, {
607 queryKey: key,
608 queryFn: () => {
609 count++
610 return 'data'
611 },
612 gcTime: 0,
613 staleTime: Infinity,
614 })
615 const unsubscribe1 = observer.subscribe(() => undefined)
616 unsubscribe1()
617 await vi.advanceTimersByTimeAsync(0)
618 expect(queryCache.find({ queryKey: key })).toBeUndefined()
619​
620 const unsubscribe2 = observer.subscribe(() => undefined)
621 unsubscribe2()
622 await vi.advanceTimersByTimeAsync(0)
623 expect(queryCache.find({ queryKey: key })).toBeUndefined()
624 expect(count).toBe(1)
625 })
626​
627 it('should be garbage collected when unsubscribed to', async () => {
628 const key = queryKey()
629 const observer = new QueryObserver(queryClient, {
630 queryKey: key,
631 queryFn: () => 'data',
632 gcTime: 0,
633 })
634​
635 expect(queryCache.find({ queryKey: key })?.state.status).toBe('pending')
636​
637 const unsubscribe = observer.subscribe(() => undefined)
638 expect(queryCache.find({ queryKey: key })?.state.status).toBe('pending')
639​
640 unsubscribe()
641 await vi.advanceTimersByTimeAsync(0)
642 expect(queryCache.find({ queryKey: key })).toBeUndefined()
643 })
644​
645 it('should be garbage collected later when unsubscribed and query is fetching', async () => {
646 const key = queryKey()
647 const observer = new QueryObserver(queryClient, {
648 queryKey: key,
649 queryFn: () => sleep(20).then(() => 'data'),
650 gcTime: 10,
651 })
652 const unsubscribe = observer.subscribe(() => undefined)
653 await vi.advanceTimersByTimeAsync(20)
654 expect(queryCache.find({ queryKey: key })?.state.data).toBe('data')
655​
656 observer.refetch()
657 unsubscribe()
658 // unsubscribe should not remove even though gcTime has elapsed b/c query is still fetching
659 expect(queryCache.find({ queryKey: key })?.state.data).toBe('data')
660 // should be removed after an additional staleTime wait
661 await vi.advanceTimersByTimeAsync(30)
662 expect(queryCache.find({ queryKey: key })).toBeUndefined()
663 })
664​
665 it('should not be garbage collected unless there are no subscribers', async () => {
666 const key = queryKey()
667 const observer = new QueryObserver(queryClient, {
668 queryKey: key,
669 queryFn: () => 'data',
670 gcTime: 0,
671 })
672​
673 expect(queryCache.find({ queryKey: key })?.state.status).toBe('pending')
674​
675 const unsubscribe = observer.subscribe(() => undefined)
676 await vi.advanceTimersByTimeAsync(100)
677 expect(queryCache.find({ queryKey: key })?.state.data).toBe('data')
678​
679 unsubscribe()
680 await vi.advanceTimersByTimeAsync(100)
681 expect(queryCache.find({ queryKey: key })).toBeUndefined()
682​
683 queryClient.setQueryData(key, 'data')
684 await vi.advanceTimersByTimeAsync(100)
685 expect(queryCache.find({ queryKey: key })?.state.data).toBe('data')
686 })
687​
688 it('should return proper count of observers', () => {
689 const key = queryKey()
690 const options = { queryKey: key, queryFn: () => 'data' }
691 const observer = new QueryObserver(queryClient, options)
692 const observer2 = new QueryObserver(queryClient, options)
693 const observer3 = new QueryObserver(queryClient, options)
694 const query = queryCache.find({ queryKey: key })
695​
696 expect(query?.getObserversCount()).toEqual(0)
697​
698 const unsubscribe1 = observer.subscribe(() => undefined)
699 const unsubscribe2 = observer2.subscribe(() => undefined)
700 const unsubscribe3 = observer3.subscribe(() => undefined)
701 expect(query?.getObserversCount()).toEqual(3)
702​
703 unsubscribe3()
704 expect(query?.getObserversCount()).toEqual(2)
705​
706 unsubscribe2()
707 expect(query?.getObserversCount()).toEqual(1)
708​
709 unsubscribe1()
710 expect(query?.getObserversCount()).toEqual(0)
711 })
712​
713 it('should store meta object in query', async () => {
714 const meta = {
715 it: 'works',
716 }
717​
718 const key = queryKey()
719​
720 await queryClient
721 .query({
722 queryKey: key,
723 queryFn: () => 'data',
724 meta,
725 })
726 .catch(noop)
727​
728 const query = queryCache.find({ queryKey: key })!
729​
730 expect(query.meta).toBe(meta)
731 expect(query.options.meta).toBe(meta)
732 })
733​
734 it('should update meta object on change', async () => {
735 const meta = {
736 it: 'works',
737 }
738​
739 const key = queryKey()
740 const queryFn = () => 'data'
741​
742 await queryClient.query({ queryKey: key, queryFn, meta }).catch(noop)
743​
744 await queryClient
745 .query({ queryKey: key, queryFn, meta: undefined })
746 .catch(noop)
747​
748 const query = queryCache.find({ queryKey: key })!
749​
750 expect(query.meta).toBeUndefined()
751 expect(query.options.meta).toBeUndefined()
752 })
753​
754 it('should use default meta', async () => {
755 const meta = {
756 it: 'works',
757 }
758​
759 const key = queryKey()
760 const queryFn = () => 'data'
761​
762 queryClient.setQueryDefaults(key, { meta })
763​
764 await queryClient.query({ queryKey: key, queryFn }).catch(noop)
765​
766 const query = queryCache.find({ queryKey: key })!
767​
768 expect(query.meta).toBe(meta)
769 })
770​
771 it('should provide meta object inside query function', async () => {
772 const meta = {
773 it: 'works',
774 }
775​
776 const queryFn = vi.fn(() => 'data')
777​
778 const key = queryKey()
779​
780 await queryClient.query({ queryKey: key, queryFn, meta }).catch(noop)
781 expect(queryFn).toHaveBeenCalledWith(
782 expect.objectContaining({
783 meta,
784 }),
785 )
786 })
787​
788 it('should refetch the observer when online method is called', () => {
789 const key = queryKey()
790​
791 const observer = new QueryObserver(queryClient, {
792 queryKey: key,
793 queryFn: () => 'data',
794 })
795​
796 const refetchSpy = vi.spyOn(observer, 'refetch')
797 const unsubscribe = observer.subscribe(() => undefined)
798 queryCache.onOnline()
799​
800 // Should refetch the observer
801 expect(refetchSpy).toHaveBeenCalledTimes(1)
802​
803 unsubscribe()
804 refetchSpy.mockRestore()
805 })
806​
807 it('should not add an existing observer', async () => {
808 const key = queryKey()
809​
810 await queryClient
811 .query({ queryKey: key, queryFn: () => 'data' })
812 .catch(noop)
813 const query = queryCache.find({ queryKey: key })!
814 expect(query.getObserversCount()).toEqual(0)
815​
816 const observer = new QueryObserver(queryClient, {
817 queryKey: key,
818 })
819​
820 expect(query.getObserversCount()).toEqual(0)
821​
822 query.addObserver(observer)
823 expect(query.getObserversCount()).toEqual(1)
824​
825 query.addObserver(observer)
826 expect(query.getObserversCount()).toEqual(1)
827 })
828​
829 it('should not try to remove an observer that does not exist', async () => {
830 const key = queryKey()
831​
832 await queryClient
833 .query({ queryKey: key, queryFn: () => 'data' })
834 .catch(noop)
835 const query = queryCache.find({ queryKey: key })!
836 const observer = new QueryObserver(queryClient, {
837 queryKey: key,
838 })
839​
840 expect(query.getObserversCount()).toEqual(0)
841​
842 const notifySpy = vi.spyOn(queryCache, 'notify')
843 expect(() => query.removeObserver(observer)).not.toThrow()
844 expect(notifySpy).not.toHaveBeenCalled()
845​
846 notifySpy.mockRestore()
847 })
848​
849 it('should notify remaining observers when one unsubscribes during an update', () => {
850 const key = queryKey()
851 const options = { queryKey: key, enabled: false }
852 const firstObserver = new QueryObserver(queryClient, options)
853 const secondObserver = new QueryObserver(queryClient, options)
854 const secondListener = vi.fn()
855​
856 let unsubscribeFirst: () => void = () => undefined
857 unsubscribeFirst = firstObserver.subscribe(() => {
858 unsubscribeFirst()
859 })
860 const unsubscribeSecond = secondObserver.subscribe(secondListener)
861​
862 queryClient.setQueryData(key, 'data')
863 expect(secondListener).toHaveBeenCalledTimes(1)
864 expect(secondObserver.getCurrentResult().data).toBe('data')
865​
866 unsubscribeSecond()
867 })
868​
869 it('should not change state on invalidate() if already invalidated', async () => {
870 const key = queryKey()
871​
872 await queryClient
873 .query({ queryKey: key, queryFn: () => 'data' })
874 .catch(noop)
875 const query = queryCache.find({ queryKey: key })!
876​
877 query.invalidate()
878 expect(query.state.isInvalidated).toBe(true)
879​
880 const previousState = query.state
881​
882 query.invalidate()
883​
884 expect(query.state).toBe(previousState)
885 })
886​
887 it('should not dispatch "fetch" from fetch if query is already fetching', async () => {
888 const key = queryKey()
889​
890 const queryFn = () => sleep(10).then(() => 'data')
891​
892 const updates: Array<string> = []
893​
894 void queryClient.query({ queryKey: key, queryFn }).catch(noop)
895 await vi.advanceTimersByTimeAsync(10)
896 const query = queryCache.find({ queryKey: key })!
897​
898 const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
899 updates.push(event.type)
900 })
901​
902 void query.fetch({
903 queryKey: key,
904 queryFn,
905 })
906​
907 query.fetch({
908 queryKey: key,
909 queryFn,
910 })
911 await vi.advanceTimersByTimeAsync(10)
912 expect(updates).toEqual([
913 'updated', // type: 'fetch'
914 'updated', // type: 'success'
915 ])
916​
917 unsubscribe()
918 })
919​
920 it('should throw an error from fetch if the queryFn is not defined', async () => {
921 const key = queryKey()
922​
923 const observer = new QueryObserver(queryClient, {
924 queryKey: key,
925 queryFn: undefined,
926 retry: false,
927 })
928​
929 const unsubscribe = observer.subscribe(() => undefined)
930 await vi.advanceTimersByTimeAsync(10)
931 const query = queryCache.find({ queryKey: key })!
932 expect(observer.getCurrentResult()).toMatchObject({
933 status: 'error',
934 error: new Error(`Missing queryFn: '${query.queryHash}'`),
935 })
936​
937 unsubscribe()
938 })
939​
940 it('should dispatch an error from fetch if the queryFn returns undefined', async () => {
941 const consoleErrorMock = vi.spyOn(console, 'error')
942 consoleErrorMock.mockImplementation(() => undefined)
943 const key = queryKey()
944​
945 const observer = new QueryObserver(queryClient, {
946 queryKey: key,
947 queryFn: () => undefined,
948 retry: false,
949 })
950​
951 let observerResult: QueryObserverResult<unknown, unknown> | undefined
952​
953 const unsubscribe = observer.subscribe((result) => {
954 observerResult = result
955 })
956 await vi.advanceTimersByTimeAsync(10)
957​
958 const error = new Error(`${JSON.stringify(key)} data is undefined`)
959​
960 expect(observerResult).toMatchObject({
961 isError: true,
962 error,
963 })
964​
965 expect(consoleErrorMock).toHaveBeenCalledWith(
966 `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ["${key}"]`,
967 )
968​
969 unsubscribe()
970 consoleErrorMock.mockRestore()
971 })
972​
973 it('should not retry on the server', async () => {
974 const resetIsServer = setIsServer(true)
975​
976 const key = queryKey()
977 let count = 0
978​
979 const observer = new QueryObserver(queryClient, {
980 queryKey: key,
981 queryFn: () => {
982 count++
983 return Promise.reject(new Error('error'))
984 },
985 })
986​
987 await observer.refetch()
988 expect(count).toBe(1)
989​
990 resetIsServer()
991 })
992​
993 it('should use an infinite garbage collection time on the server', () => {
994 const resetIsServer = setIsServer(true)
995​
996 try {
997 const query = queryCache.build(queryClient, {
998 queryKey: queryKey(),
999 queryFn: () => 'data',
1000 })
1001​
1002 expect(query.gcTime).toBe(Infinity)
1003 } finally {
1004 resetIsServer()
1006 })
1007​
1008 it('should call initialDataUpdatedAt in constructor if defined as a function', async () => {
1009 const key = queryKey()
1010​
1011 const initialDataUpdatedAtSpy = vi.fn()
1012​
1013 await queryClient
1014 .query({
1015 queryKey: key,
1016 queryFn: () => 'data',
1017 initialData: 'initial',
1018 initialDataUpdatedAt: initialDataUpdatedAtSpy,
1019 })
1020 .catch(noop)
1021 expect(initialDataUpdatedAtSpy).toHaveBeenCalled()
1022 })
1023​
1024 it('should work with initialDataUpdatedAt set to zero', async () => {
1025 const key = queryKey()
1026​
1027 await queryClient
1028 .query({
1029 queryKey: key,
1030 queryFn: () => 'data',
1031 staleTime: Infinity,
1032 initialData: 'initial',
1033 initialDataUpdatedAt: 0,
1034 })
1035 .catch(noop)
1036 expect(queryCache.find({ queryKey: key })?.state).toMatchObject({
1037 data: 'initial',
1038 status: 'success',
1039 dataUpdatedAt: 0,
1040 })
1041 })
1042​
1043 it('should garbage collect queries even if they never fetched', async () => {
1044 const key = queryKey()
1045​
1046 queryClient.setQueryDefaults(key, { gcTime: 10 })
1047​
1048 const fn = vi.fn()
1049​
1050 const unsubscribe = queryClient.getQueryCache().subscribe(fn)
1051​
1052 queryClient.setQueryData(key, 'data')
1053 const query = queryClient.getQueryCache().find({ queryKey: key })
1054​
1055 await vi.advanceTimersByTimeAsync(10)
1056 expect(fn).toHaveBeenLastCalledWith({ type: 'removed', query })
1057​
1058 expect(queryClient.getQueryCache().findAll()).toHaveLength(0)
1059​
1060 unsubscribe()
1061 })
1062​
1063 it('should always revert to idle state (#5968)', async () => {
1064 let mockedData = [1]
1065​
1066 const key = queryKey()
1067​
1068 const queryFn = vi
1069 .fn<
1071 context: QueryFunctionContext<ReturnType<typeof queryKey>>,
1072 ) => Promise<unknown>
1073 >()
1074 .mockImplementation(
1075 ({ signal }) =>
1076 new Promise((resolve, reject) => {
1077 const abortListener = () => {
1078 clearTimeout(timerId)
1079 reject(signal.reason)
1081 signal.addEventListener('abort', abortListener)
1082​
1083 const timerId = setTimeout(() => {
1084 signal.removeEventListener('abort', abortListener)
1085 resolve(mockedData.join(' - '))
1086 }, 50)
1087 }),
1089​
1090 const observer = new QueryObserver(queryClient, {
1091 queryKey: key,
1092 queryFn,
1093 })
1094 const unsubscribe = observer.subscribe(() => undefined)
1095 await vi.advanceTimersByTimeAsync(50) // let it resolve
1096 expect(observer.getCurrentResult().data).toBe('1')
1097 expect(observer.getCurrentResult().fetchStatus).toBe('idle')
1098​
1099 mockedData = [1, 2] // update "server" state in the background
1100​
1101 void queryClient.invalidateQueries({ queryKey: key })
1102 await vi.advanceTimersByTimeAsync(5)
1103 void queryClient.invalidateQueries({ queryKey: key })
1104 await vi.advanceTimersByTimeAsync(5)
1105 unsubscribe() // unsubscribe to simulate unmount
1106 await vi.advanceTimersByTimeAsync(5)
1107​
1108 // reverted to previous data and idle fetchStatus
1109 expect(queryCache.find({ queryKey: key })?.state).toMatchObject({
1110 status: 'success',
1111 data: '1',
1112 fetchStatus: 'idle',
1113 })
1114​
1115 // set up a new observer to simulate a mount of new component
1116 const newObserver = new QueryObserver(queryClient, {
1117 queryKey: key,
1118 queryFn,
1119 })
1120 const spy = vi.fn()
1121 newObserver.subscribe(({ data }) => spy(data))
1122 await vi.advanceTimersByTimeAsync(60) // let it resolve
1123 expect(spy).toHaveBeenCalledWith('1 - 2')
1124 })
1125​
1126 it('should not reject a promise when silently cancelled in the background', async () => {
1127 const key = queryKey()
1128​
1129 let x = 0
1130​
1131 queryClient.setQueryData(key, 'initial')
1132 const queryFn = vi
1133 .fn()
1134 .mockImplementation(() => sleep(100).then(() => 'data' + x))
1135​
1136 const promise = queryClient.query({
1137 queryKey: key,
1138 queryFn,
1139 })
1140 await vi.advanceTimersByTimeAsync(0)
1141 expect(queryFn).toHaveBeenCalledTimes(1)
1142​
1143 x = 1
1144​
1145 // cancel ongoing re-fetches
1146 void queryClient.refetchQueries({ queryKey: key }, { cancelRefetch: true })
1147​
1148 // The promise should not reject
1149 await vi.advanceTimersByTimeAsync(100)
1150 await expect(promise).resolves.toBe('data1')
1151​
1152 expect(queryFn).toHaveBeenCalledTimes(2)
1153 })
1154​
1155 it('should have an error log when queryFn data is not serializable', async () => {
1156 const consoleErrorMock = vi.spyOn(console, 'error')
1157​
1158 consoleErrorMock.mockImplementation(() => undefined)
1159​
1160 const key = queryKey()
1161​
1162 const queryFn = vi.fn()
1163​
1164 const initialData = {
1165 foo: 'bar',
1167​
1168 const data = {
1169 get foo(): void {
1170 return this.foo
1171 },
1173​
1174 queryFn.mockImplementation(() => sleep(10).then(() => data))
1175​
1176 void queryClient
1177 .query({
1178 queryKey: key,
1179 queryFn,
1180 initialData,
1181 })
1182 .catch(noop)
1183 await vi.advanceTimersByTimeAsync(10)
1184​
1185 const query = queryCache.find({ queryKey: key })!
1186​
1187 expect(queryFn).toHaveBeenCalledTimes(1)
1188​
1189 expect(query.state.status).toBe('error')
1190 expect(query.state.error?.message).toContain(
1191 'Maximum call stack size exceeded',
1193​
1194 expect(consoleErrorMock).toHaveBeenCalledWith(
1195 expect.stringContaining(
1196 'Structural sharing requires data to be JSON serializable',
1197 ),
1199​
1200 consoleErrorMock.mockRestore()
1201 })
1202​
1203 it('should have an error status when setData has any error inside', async () => {
1204 const key = queryKey()
1205​
1206 const queryFn = vi
1207 .fn<() => Promise<string>>()
1208 .mockImplementation(() => sleep(10).then(() => 'data'))
1209​
1210 void queryClient
1211 .query({
1212 queryKey: key,
1213 queryFn,
1214 structuralSharing: () => {
1215 throw Error('Any error')
1216 },
1217 })
1218 .catch(noop)
1219​
1220 const query = queryCache.find({ queryKey: key })!
1221​
1222 expect(queryFn).toHaveBeenCalledTimes(1)
1223 await vi.advanceTimersByTimeAsync(10)
1224 expect(query.state.status).toBe('error')
1225 })
1226​
1227 it('should use persister if provided', async () => {
1228 const key = queryKey()
1229​
1230 await queryClient
1231 .query({
1232 queryKey: key,
1233 queryFn: () => 'data',
1234 persister: () => Promise.resolve('persisted data'),
1235 })
1236 .catch(noop)
1237​
1238 const query = queryCache.find({ queryKey: key })!
1239 expect(query.state.data).toBe('persisted data')
1240 })
1241​
1242 it('should use queryFn from observer if not provided in options', async () => {
1243 const key = queryKey()
1244 const queryFn = () => Promise.resolve('data')
1245 const observer = new QueryObserver(queryClient, {
1246 queryKey: key,
1247 queryFn: queryFn,
1248 })
1249​
1250 const query = new Query({
1251 client: queryClient,
1252 queryKey: key,
1253 queryHash: hashQueryKeyByOptions(key),
1254 })
1255​
1256 query.addObserver(observer)
1257​
1258 await query.fetch()
1259 const result = await query.state.data
1260 expect(result).toBe('data')
1261 expect(query.options.queryFn).toBe(queryFn)
1262 })
1263​
1264 it('should log error when queryKey is not an array', async () => {
1265 const consoleErrorMock = vi.spyOn(console, 'error')
1266 const key: unknown = 'string-key'
1267​
1268 await queryClient
1269 .query({
1270 queryKey: key as QueryKey,
1271 queryFn: () => 'data',
1272 })
1273 .catch(noop)
1274 expect(consoleErrorMock).toHaveBeenCalledWith(
1275 "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']",
1277​
1278 consoleErrorMock.mockRestore()
1279 })
1280​
1281 it('should call initialData function when it is a function', () => {
1282 const key = queryKey()
1283 const initialDataFn = vi.fn(() => 'initial data')
1284​
1285 const query = new Query({
1286 client: queryClient,
1287 queryKey: key,
1288 queryHash: hashQueryKeyByOptions(key),
1289 options: {
1290 queryFn: () => 'data',
1291 initialData: initialDataFn,
1292 },
1293 })
1294​
1295 expect(initialDataFn).toHaveBeenCalledTimes(1)
1296 expect(query.state.data).toBe('initial data')
1297 })
1298​
1299 it('should update initialData when Query exists without data', async () => {
1300 const key = queryKey()
1301 const queryFn = vi.fn(() => sleep(100).then(() => 'data'))
1302​
1303 const promise = queryClient
1304 .query({
1305 queryKey: key,
1306 queryFn,
1307 staleTime: 1000,
1308 })
1309 .catch(noop)
1310 vi.advanceTimersByTime(50)
1311 expect(queryClient.getQueryState(key)).toMatchObject({
1312 data: undefined,
1313 status: 'pending',
1314 fetchStatus: 'fetching',
1315 })
1316​
1317 const observer = new QueryObserver(queryClient, {
1318 queryKey: key,
1319 queryFn,
1320 staleTime: 1000,
1321 initialData: 'initialData',
1322 initialDataUpdatedAt: 10,
1323 })
1324​
1325 const unsubscribe = observer.subscribe(vi.fn())
1326 expect(queryClient.getQueryState(key)).toMatchObject({
1327 data: 'initialData',
1328 dataUpdatedAt: 10,
1329 status: 'success',
1330 fetchStatus: 'fetching',
1331 })
1332 vi.advanceTimersByTime(50)
1333 await promise
1334 expect(queryClient.getQueryState(key)).toMatchObject({
1335 data: 'data',
1336 status: 'success',
1337 fetchStatus: 'idle',
1338 })
1339​
1340 expect(queryFn).toHaveBeenCalledTimes(1)
1341​
1342 unsubscribe()
1343​
1344 // resetting should get us back ot 'initialData'
1345 queryClient.getQueryCache().find({ queryKey: key })!.reset()
1346​
1347 expect(queryClient.getQueryState(key)).toMatchObject({
1348 data: 'initialData',
1349 status: 'success',
1350 fetchStatus: 'idle',
1351 })
1352 })
1353​
1354 it('should not override fetching state when revert happens after new observer subscribes', async () => {
1355 const key = queryKey()
1356 let count = 0
1357​
1358 const queryFn = vi.fn(async ({ signal: _signal }) => {
1359 // Destructure `signal` to intentionally consume it so observer-removal uses revert-cancel path
1360 await sleep(50)
1361 return 'data' + count++
1362 })
1363​
1364 const query = new Query({
1365 client: queryClient,
1366 queryKey: key,
1367 queryHash: hashQueryKeyByOptions(key),
1368 options: { queryFn },
1369 })
1370​
1371 const observer1 = new QueryObserver(queryClient, {
1372 queryKey: key,
1373 queryFn,
1374 })
1375​
1376 query.addObserver(observer1)
1377 const promise1 = query.fetch()
1378 await vi.advanceTimersByTimeAsync(10)
1379​
1380 query.removeObserver(observer1)
1381​
1382 const observer2 = new QueryObserver(queryClient, {
1383 queryKey: key,
1384 queryFn,
1385 })
1386​
1387 query.addObserver(observer2)
1388​
1389 query.fetch()
1390 await expect(promise1).rejects.toBeInstanceOf(CancelledError)
1391 await vi.advanceTimersByTimeAsync(50)
1392 expect(query.state.fetchStatus).toBe('idle')
1393​
1394 expect(queryFn).toHaveBeenCalledTimes(2)
1395​
1396 expect(query.state).toMatchObject({
1397 fetchStatus: 'idle',
1398 status: 'success',
1399 data: 'data1',
1400 })
1401 })
1402​
1403 it('should not increment dataUpdateCount when setting initialData on prefetched query', async () => {
1404 const key = queryKey()
1405 const queryFn = vi.fn().mockImplementation(() => 'fetched-data')
1406​
1407 // First prefetch the query (creates query without data)
1408 void queryClient
1409 .query({
1410 queryKey: key,
1411 queryFn,
1412 })
1413 .catch(noop)
1414​
1415 const query = queryCache.find({ queryKey: key })!
1416 expect(query.state.data).toBeUndefined()
1417 expect(query.state.dataUpdateCount).toBe(0)
1418​
1419 // Now create an observer with initialData
1420 const observer = new QueryObserver(queryClient, {
1421 queryKey: key,
1422 queryFn,
1423 initialData: 'initial-data',
1424 })
1425​
1426 // The query should now have the initial data but dataUpdateCount should still be 0
1427 // since this was not fetched data but initial data
1428 expect(query.state.data).toBe('initial-data')
1429 expect(query.state.dataUpdateCount).toBe(0)
1430​
1431 // Get the initial state as captured by the observer
1432 const result = observer.getCurrentResult()
1433 expect(result.data).toBe('initial-data')
1434 expect(result.isFetchedAfterMount).toBe(false) // This should be false since no actual fetch occurred
1435​
1436 // Now trigger a refetch through the observer to simulate real-world usage
1437 await observer.refetch()
1438​
1439 // After actual fetch, dataUpdateCount should increment
1440 expect(query.state.dataUpdateCount).toBe(1)
1441 expect(query.state.data).toBe('fetched-data')
1442​
1443 // And isFetchedAfterMount should now be true
1444 const updatedResult = observer.getCurrentResult()
1445 expect(updatedResult.isFetchedAfterMount).toBe(true)
1446 })