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