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