Open History to see the last commit
1import {
2 afterAll,
3 afterEach,
4 beforeAll,
5 beforeEach,
6 describe,
7 expect,
8 it,
9 vi,
10} from 'vitest'
11import { act, fireEvent, render } from '@testing-library/react'
12import * as React from 'react'
13import { ErrorBoundary } from 'react-error-boundary'
14import { queryKey, sleep } from '@tanstack/query-test-utils'
15import {
16 QueryClient,
17 skipToken,
18 useSuspenseQueries,
19 useSuspenseQuery,
20} from '..'
21import { renderWithClient } from './utils'
22import type { UseSuspenseQueryOptions } from '..'
23β
24type NumberQueryOptions = UseSuspenseQueryOptions<number>
25β
26const QUERY_DURATION = 1000
27β
28const createQuery: (id: number) => NumberQueryOptions = (id) => ({
29 queryKey: [id],
30 queryFn: () => sleep(QUERY_DURATION).then(() => id),
31})
32const resolveQueries = () => vi.advanceTimersByTimeAsync(QUERY_DURATION)
33β
34const queryClient = new QueryClient()
35β
36describe('useSuspenseQueries', () => {
37 const onSuspend = vi.fn()
38 const onQueriesResolution = vi.fn()
39β
40 beforeAll(() => {
41 vi.useFakeTimers()
42 })
43β
44 afterAll(() => {
45 vi.useRealTimers()
46 })
47β
48 afterEach(() => {
49 queryClient.clear()
50 onSuspend.mockClear()
51 onQueriesResolution.mockClear()
52 })
53β
54 function SuspenseFallback() {
55 React.useEffect(() => {
56 onSuspend()
57 }, [])
58β
59 return <div>loading</div>
60 }
61β
62 const withSuspenseWrapper = <T extends object>(Component: React.FC<T>) => {
63 function SuspendedComponent(props: T) {
64 return (
65 <React.Suspense fallback={<SuspenseFallback />}>
66 <Component {...props} />
67 </React.Suspense>
68 )
69 }
70β
71 return SuspendedComponent
72 }
73β
74 function QueriesContainer({
75 queries,
76 }: {
77 queries: Array<NumberQueryOptions>
78 }) {
79 const queriesResults = useSuspenseQueries(
80 { queries, combine: (results) => results.map((r) => r.data) },
81 queryClient,
82 )
83β
84 React.useEffect(() => {
85 onQueriesResolution(queriesResults)
86 }, [queriesResults])
87β
88 return null
89 }
90β
91 const TestComponent = withSuspenseWrapper(QueriesContainer)
92β
93 it('should suspend on mount', () => {
94 render(<TestComponent queries={[1, 2].map(createQuery)} />)
95β
96 expect(onSuspend).toHaveBeenCalledOnce()
97 })
98β
99 it('should resolve queries', async () => {
100 render(<TestComponent queries={[1, 2].map(createQuery)} />)
101β
102 await act(resolveQueries)
103β
104 expect(onQueriesResolution).toHaveBeenCalledTimes(1)
105 expect(onQueriesResolution).toHaveBeenLastCalledWith([1, 2])
106 })
107β
108 it('should not suspend on mount if query has been already fetched', () => {
109 const query = createQuery(1)
110β
111 queryClient.setQueryData(query.queryKey, query.queryFn)
112β
113 render(<TestComponent queries={[query]} />)
114β
115 expect(onSuspend).not.toHaveBeenCalled()
116 })
117β
118 it('should not break suspense when queries change without resolving', async () => {
119 const initQueries = [1, 2].map(createQuery)
120 const nextQueries = [3, 4, 5, 6].map(createQuery)
121β
122 const { rerender } = render(<TestComponent queries={initQueries} />)
123β
124 rerender(<TestComponent queries={nextQueries} />)
125β
126 await act(resolveQueries)
127β
128 expect(onSuspend).toHaveBeenCalledTimes(1)
129 expect(onQueriesResolution).toHaveBeenCalledTimes(1)
130 expect(onQueriesResolution).toHaveBeenLastCalledWith([3, 4, 5, 6])
131 })
132β
133 it('should suspend only once per queries change', async () => {
134 const initQueries = [1, 2].map(createQuery)
135 const nextQueries = [3, 4, 5, 6].map(createQuery)
136β
137 const { rerender } = render(<TestComponent queries={initQueries} />)
138β
139 await act(resolveQueries)
140β
141 rerender(<TestComponent queries={nextQueries} />)
142β
143 await act(resolveQueries)
144β
145 expect(onSuspend).toHaveBeenCalledTimes(2)
146 expect(onQueriesResolution).toHaveBeenCalledTimes(2)
147 expect(onQueriesResolution).toHaveBeenLastCalledWith([3, 4, 5, 6])
148 })
149β
150 it('should only call combine after resolving', async () => {
151 const spy = vi.fn()
152 const key = queryKey()
153β
154 function Page() {
155 const data = useSuspenseQueries({
156 queries: [1, 2, 3].map((value) => ({
157 queryKey: [...key, { value }],
158 queryFn: () => sleep(value * 10).then(() => ({ value: value * 10 })),
159 })),
160 combine: (result) => {
161 spy(result)
162 return 'data'
163 },
164 })
165β
166 return <h1>{data}</h1>
167 }
168β
169 const rendered = renderWithClient(
170 queryClient,
171 <React.Suspense fallback="loading">
172 <Page />
173 </React.Suspense>,
174 )
175β
176 expect(rendered.getByText('loading')).toBeInTheDocument()
177β
178 expect(spy).not.toHaveBeenCalled()
179β
180 await act(() => vi.advanceTimersByTimeAsync(30))
181 expect(rendered.getByText('data')).toBeInTheDocument()
182β
183 expect(spy).toHaveBeenCalled()
184 })
185β
186 it('should handle duplicate query keys without infinite loops', async () => {
187 const key = queryKey()
188 const localDuration = 10
189 let renderCount = 0
190β
191 function getUserData() {
192 return {
193 queryKey: key,
194 queryFn: async () => {
195 await sleep(localDuration)
196 return { name: 'John Doe', age: 50 }
197 },
198 }
199 }
200β
201 function getName() {
202 return {
203 ...getUserData(),
204 select: (data: any) => data.name,
205 }
206 }
207β
208 function getAge() {
209 return {
210 ...getUserData(),
211 select: (data: any) => data.age,
212 }
213 }
214β
215 function App() {
216 renderCount++
217 const [{ data }, { data: data2 }] = useSuspenseQueries({
218 queries: [getName(), getAge()],
219 })
220β
221 React.useEffect(() => {
222 onQueriesResolution({ data, data2 })
223 }, [data, data2])
224β
225 return (
226 <div>
227 <h1>Data</h1>
228 {JSON.stringify({ data }, null, 2)}
229 {JSON.stringify({ data2 }, null, 2)}
230 </div>
231 )
232 }
233β
234 renderWithClient(
235 queryClient,
236 <React.Suspense fallback={<SuspenseFallback />}>
237 <App />
238 </React.Suspense>,
239 )
240β
241 await act(() => vi.advanceTimersByTimeAsync(localDuration))
242β
243 expect(onSuspend).toHaveBeenCalledTimes(1)
244 expect(onQueriesResolution).toHaveBeenCalledTimes(1)
245β
246 await act(() => vi.advanceTimersByTimeAsync(100))
247β
248 expect(onQueriesResolution).toHaveBeenCalledTimes(1)
249 expect(onQueriesResolution).toHaveBeenLastCalledWith({
250 data: 'John Doe',
251 data2: 50,
252 })
253β
254 // With the infinite loop bug, renderCount would be very high (e.g. > 100)
255 // Without bug, it should be small (initial suspend + resolution = 2-3)
256 expect(renderCount).toBeLessThan(10)
257 })
258})
259β
260describe('useSuspenseQueries 2', () => {
261 beforeEach(() => {
262 vi.useFakeTimers()
263 })
264β
265 afterEach(() => {
266 vi.useRealTimers()
267 })
268β
269 it('should suspend all queries in parallel', async () => {
270 const key1 = queryKey()
271 const key2 = queryKey()
272 const results: Array<string> = []
273β
274 function Fallback() {
275 results.push('loading')
276 return <div>loading</div>
277 }
278β
279 function Page() {
280 const result = useSuspenseQueries({
281 queries: [
282 {
283 queryKey: key1,
284 queryFn: () =>
285 sleep(10).then(() => {
286 results.push('1')
287 return '1'
288 }),
289 },
290 {
291 queryKey: key2,
292 queryFn: () =>
293 sleep(20).then(() => {
294 results.push('2')
295 return '2'
296 }),
297 },
298 ],
299 })
300β
301 return (
302 <div>
303 <h1>data: {result.map((item) => item.data ?? 'null').join(',')}</h1>
304 </div>
305 )
306 }
307β
308 const rendered = renderWithClient(
309 queryClient,
310 <React.Suspense fallback={<Fallback />}>
311 <Page />
312 </React.Suspense>,
313 )
314β
315 expect(rendered.getByText('loading')).toBeInTheDocument()
316 await act(() => vi.advanceTimersByTimeAsync(20))
317 expect(rendered.getByText('data: 1,2')).toBeInTheDocument()
318β
319 expect(results).toEqual(['loading', '1', '2'])
320 })
321β
322 it("shouldn't unmount before all promises fetched", async () => {
323 const key1 = queryKey()
324 const key2 = queryKey()
325 const results: Array<string> = []
326 const refs: Array<number> = []
327β
328 function Fallback() {
329 results.push('loading')
330 return <div>loading</div>
331 }
332β
333 function Page() {
334 // eslint-disable-next-line react-hooks/purity
335 const ref = React.useRef(Math.random())
336 const result = useSuspenseQueries({
337 queries: [
338 {
339 queryKey: key1,
340 queryFn: () =>
341 sleep(10).then(() => {
342 refs.push(ref.current)
343 results.push('1')
344 return '1'
345 }),
346 },
347 {
348 queryKey: key2,
349 queryFn: () =>
350 sleep(20).then(() => {
351 refs.push(ref.current)
352 results.push('2')
353 return '2'
354 }),
355 },
356 ],
357 })
358β
359 return (
360 <div>
361 <h1>data: {result.map((item) => item.data ?? 'null').join(',')}</h1>
362 </div>
363 )
364 }
365β
366 const rendered = renderWithClient(
367 queryClient,
368 <React.Suspense fallback={<Fallback />}>
369 <Page />
370 </React.Suspense>,
371 )
372β
373 expect(rendered.getByText('loading')).toBeInTheDocument()
374β
375 await act(() => vi.advanceTimersByTimeAsync(20))
376 expect(rendered.getByText('data: 1,2')).toBeInTheDocument()
377β
378 expect(refs.length).toBe(2)
379 expect(refs[0]).toBe(refs[1])
380 })
381β
382 // this addresses the following issue:
383 // https://github.com/TanStack/query/issues/6344
384 it('should suspend on offline when query changes, and data should not be undefined', async () => {
385 function Page() {
386 const [id, setId] = React.useState(0)
387β
388 const { data } = useSuspenseQuery({
389 queryKey: [id],
390 queryFn: () => sleep(10).then(() => `Data ${id}`),
391 })
392β
393 // defensive guard here
394 if (data === undefined) {
395 throw new Error('data cannot be undefined')
396 }
397β
398 return (
399 <>
400 <div>{data}</div>
401 <button onClick={() => setId(id + 1)}>fetch</button>
402 </>
403 )
404 }
405β
406 const rendered = renderWithClient(
407 queryClient,
408 <React.Suspense fallback={<div>loading</div>}>
409 <Page />
410 </React.Suspense>,
411 )
412β
413 expect(rendered.getByText('loading')).toBeInTheDocument()
414 await act(() => vi.advanceTimersByTimeAsync(10))
415 expect(rendered.getByText('Data 0')).toBeInTheDocument()
416β
417 // go offline
418 document.dispatchEvent(new CustomEvent('offline'))
419β
420 fireEvent.click(rendered.getByText('fetch'))
421 expect(rendered.getByText('Data 0')).toBeInTheDocument()
422β
423 // go back online
424 document.dispatchEvent(new CustomEvent('online'))
425β
426 fireEvent.click(rendered.getByText('fetch'))
427 expect(rendered.getByText('loading')).toBeInTheDocument()
428 await act(() => vi.advanceTimersByTimeAsync(10))
429 // query should resume
430 expect(rendered.getByText('Data 1')).toBeInTheDocument()
431 })
432β
433 it('should throw error when queryKey changes and new query fails', async () => {
434 const consoleMock = vi
435 .spyOn(console, 'error')
436 .mockImplementation(() => undefined)
437 const key = queryKey()
438β
439 function Page() {
440 const [fail, setFail] = React.useState(false)
441 const { data } = useSuspenseQuery({
442 queryKey: [key, fail],
443 queryFn: () =>
444 sleep(10).then(() => {
445 if (fail) throw new Error('Suspense Error Bingo')
446 return 'data'
447 }),
448 retry: 0,
449 })
450β
451 return (
452 <div>
453 <button onClick={() => setFail(true)}>trigger fail</button>
454 <div>rendered: {data}</div>
455 </div>
456 )
457 }
458β
459 const rendered = renderWithClient(
460 queryClient,
461 <ErrorBoundary fallbackRender={() => <div>error boundary</div>}>
462 <React.Suspense fallback="loading">
463 <Page />
464 </React.Suspense>
465 </ErrorBoundary>,
466 )
467β
468 expect(rendered.getByText('loading')).toBeInTheDocument()
469 await act(() => vi.advanceTimersByTimeAsync(10))
470 expect(rendered.getByText('rendered: data')).toBeInTheDocument()
471β
472 fireEvent.click(rendered.getByText('trigger fail'))
473 expect(rendered.getByText('loading')).toBeInTheDocument()
474 await act(() => vi.advanceTimersByTimeAsync(10))
475 expect(rendered.getByText('error boundary')).toBeInTheDocument()
476β
477 expect(consoleMock.mock.calls[0]?.[1]).toStrictEqual(
478 new Error('Suspense Error Bingo'),
479 )
480β
481 consoleMock.mockRestore()
482 })
483β
484 it('should keep previous data when wrapped in a transition', async () => {
485 const key = queryKey()
486β
487 function Page() {
488 const [count, setCount] = React.useState(0)
489 const [isPending, startTransition] = React.useTransition()
490 const { data } = useSuspenseQuery({
491 queryKey: [key, count],
492 queryFn: () => sleep(10).then(() => 'data' + count),
493 })
494β
495 return (
496 <div>
497 <button onClick={() => startTransition(() => setCount(count + 1))}>
498 inc
499 </button>
500β
501 <div>{isPending ? 'pending' : data}</div>
502 </div>
503 )
504 }
505β
506 const rendered = renderWithClient(
507 queryClient,
508 <React.Suspense fallback="loading">
509 <Page />
510 </React.Suspense>,
511 )
512β
513 expect(rendered.getByText('loading')).toBeInTheDocument()
514 await act(() => vi.advanceTimersByTimeAsync(10))
515 expect(rendered.getByText('data0')).toBeInTheDocument()
516β
517 fireEvent.click(rendered.getByText('inc'))
518 expect(rendered.getByText('pending')).toBeInTheDocument()
519 await act(() => vi.advanceTimersByTimeAsync(10))
520 expect(rendered.getByText('data1')).toBeInTheDocument()
521 })
522β
523 it('should not request old data inside transitions (issue #6486)', async () => {
524 const key = queryKey()
525 let queryFnCount = 0
526β
527 function App() {
528 const [count, setCount] = React.useState(0)
529β
530 return (
531 <div>
532 <button
533 onClick={() => React.startTransition(() => setCount(count + 1))}
534 >
535 inc
536 </button>
537 <React.Suspense fallback="loading">
538 <Page count={count} />
539 </React.Suspense>
540 </div>
541 )
542 }
543β
544 function Page({ count }: { count: number }) {
545 const { data } = useSuspenseQuery({
546 queryKey: [key, count],
547 queryFn: () =>
548 sleep(10).then(() => {
549 queryFnCount++
550 return 'data' + count
551 }),
552 })
553β
554 return (
555 <div>
556 <div>{String(data)}</div>
557 </div>
558 )
559 }
560β
561 const rendered = renderWithClient(
562 queryClient,
563β
564 <App />,
565 )
566β
567 expect(rendered.getByText('loading')).toBeInTheDocument()
568 await act(() => vi.advanceTimersByTimeAsync(10))
569 expect(rendered.getByText('data0')).toBeInTheDocument()
570β
571 fireEvent.click(rendered.getByText('inc'))
572 await act(() => vi.advanceTimersByTimeAsync(10))
573 expect(rendered.getByText('data1')).toBeInTheDocument()
574β
575 expect(queryFnCount).toBe(2)
576 })
577β
578 it('should still suspense if queryClient has placeholderData config', async () => {
579 const key = queryKey()
580 const queryClientWithPlaceholder = new QueryClient({
581 defaultOptions: {
582 queries: {
583 placeholderData: (previousData: any) => previousData,
584 },
585 },
586 })
587β
588 function Page() {
589 const [count, setCount] = React.useState(0)
590 const [isPending, startTransition] = React.useTransition()
591 const { data } = useSuspenseQuery({
592 queryKey: [key, count],
593 queryFn: () => sleep(10).then(() => 'data' + count),
594 })
595β
596 return (
597 <div>
598 <button onClick={() => startTransition(() => setCount(count + 1))}>
599 inc
600 </button>
601 <div>{isPending ? 'pending' : data}</div>
602 </div>
603 )
604 }
605β
606 const rendered = renderWithClient(
607 queryClientWithPlaceholder,
608 <React.Suspense fallback="loading">
609 <Page />
610 </React.Suspense>,
611 )
612β
613 expect(rendered.getByText('loading')).toBeInTheDocument()
614 await act(() => vi.advanceTimersByTimeAsync(10))
615 expect(rendered.getByText('data0')).toBeInTheDocument()
616β
617 fireEvent.click(rendered.getByText('inc'))
618 expect(rendered.getByText('pending')).toBeInTheDocument()
619 await act(() => vi.advanceTimersByTimeAsync(10))
620 expect(rendered.getByText('data1')).toBeInTheDocument()
621 })
622β
623 it('should show error boundary even with gcTime:0 (#7853)', async () => {
624 const consoleMock = vi
625 .spyOn(console, 'error')
626 .mockImplementation(() => undefined)
627 const key = queryKey()
628 let count = 0
629β
630 function Page() {
631 useSuspenseQuery({
632 queryKey: key,
633 queryFn: () =>
634 sleep(10).then(() => {
635 count++
636 throw new Error('Query failed')
637 }),
638 gcTime: 0,
639 retry: false,
640 })
641β
642 return null
643 }
644β
645 function App() {
646 return (
647 <React.Suspense fallback="loading">
648 <ErrorBoundary
649 fallbackRender={() => {
650 return <div>There was an error!</div>
651 }}
652 >
653 <Page />
654 </ErrorBoundary>
655 </React.Suspense>
656 )
657 }
658β
659 const rendered = renderWithClient(queryClient, <App />)
660β
661 expect(rendered.getByText('loading')).toBeInTheDocument()
662 await act(() => vi.advanceTimersByTimeAsync(10))
663 expect(rendered.getByText('There was an error!')).toBeInTheDocument()
664β
665 expect(count).toBe(1)
666β
667 consoleMock.mockRestore()
668 })
669β
670 describe('gc (with fake timers)', () => {
671 beforeAll(() => {
672 vi.useFakeTimers()
673 })
674β
675 afterAll(() => {
676 vi.useRealTimers()
677 })
678β
679 it('should gc when unmounted while fetching with low gcTime (#8159)', async () => {
680 const key = queryKey()
681β
682 function Page() {
683 return (
684 <React.Suspense fallback="loading">
685 <Component />
686 </React.Suspense>
687 )
688 }
689β
690 function Component() {
691 const { data } = useSuspenseQuery({
692 queryKey: key,
693 queryFn: () => sleep(3000).then(() => 'data'),
694 gcTime: 1000,
695 })
696β
697 return <div>{data}</div>
698 }
699β
700 function Page2() {
701 return <div>page2</div>
702 }
703β
704 function App() {
705 const [show, setShow] = React.useState(true)
706β
707 return (
708 <div>
709 {show ? <Page /> : <Page2 />}
710 <button onClick={() => setShow(false)}>hide</button>
711 </div>
712 )
713 }
714β
715 const rendered = renderWithClient(queryClient, <App />)
716β
717 expect(rendered.getByText('loading')).toBeInTheDocument()
718β
719 fireEvent.click(rendered.getByText('hide'))
720 expect(rendered.getByText('page2')).toBeInTheDocument()
721 // wait for query to be resolved
722 await act(() => vi.advanceTimersByTimeAsync(3000))
723 expect(queryClient.getQueryData(key)).toBe('data')
724 // wait for gc
725 await act(() => vi.advanceTimersByTimeAsync(1000))
726 expect(queryClient.getQueryData(key)).toBe(undefined)
727 })
728 })
729β
730 it('should log an error when skipToken is passed as queryFn', () => {
731 const consoleErrorSpy = vi
732 .spyOn(console, 'error')
733 .mockImplementation(() => {})
734 const key = queryKey()
735β
736 function Page() {
737 useSuspenseQueries({
738 queries: [
739 {
740 queryKey: key,
741 // @ts-expect-error
742 // eslint-disable-next-line react-hooks/purity
743 queryFn: Math.random() >= 0 ? skipToken : () => Promise.resolve(5),
744 },
745 ],
746 })
747β
748 return null
749 }
750β
751 function App() {
752 return (
753 <React.Suspense fallback="loading">
754 <Page />
755 </React.Suspense>
756 )
757 }
758β
759 renderWithClient(queryClient, <App />)
760β
761 expect(consoleErrorSpy).toHaveBeenCalledWith(
762 'skipToken is not allowed for useSuspenseQueries',
763 )
764 consoleErrorSpy.mockRestore()
765 })
766β
767 it('should log an error when skipToken is used in development environment', () => {
768 const envCopy = process.env.NODE_ENV
769 process.env.NODE_ENV = 'development'
770β
771 const consoleErrorSpy = vi
772 .spyOn(console, 'error')
773 .mockImplementation(() => undefined)
774 const key = queryKey()
775β
776 function Page() {
777 useSuspenseQueries({
778 queries: [
779 {
780 queryKey: key,
781 queryFn: skipToken as any,
782 },
783 ],
784 })
785β
786 return null
787 }
788β
789 renderWithClient(
790 queryClient,
791 <React.Suspense fallback="loading">
792 <Page />
793 </React.Suspense>,
794 )
795β
796 expect(consoleErrorSpy).toHaveBeenCalledWith(
797 'skipToken is not allowed for useSuspenseQueries',
798 )
799 consoleErrorSpy.mockRestore()
800 process.env.NODE_ENV = envCopy
801 })
802β
803 it('should not log an error when skipToken is used in production environment', () => {
804 const envCopy = process.env.NODE_ENV
805 process.env.NODE_ENV = 'production'
806β
807 const consoleErrorSpy = vi
808 .spyOn(console, 'error')
809 .mockImplementation(() => undefined)
810 const key = queryKey()
811β
812 function Page() {
813 useSuspenseQueries({
814 queries: [
815 {
816 queryKey: key,
817 queryFn: skipToken as any,
818 },
819 ],
820 })
821β
822 return null
823 }
824β
825 renderWithClient(
826 queryClient,
827 <React.Suspense fallback="loading">
828 <Page />
829 </React.Suspense>,
830 )
831β
832 expect(consoleErrorSpy).not.toHaveBeenCalled()
833 consoleErrorSpy.mockRestore()
834 process.env.NODE_ENV = envCopy
835 })
836β
837 it('should only suspend queries that are pending when the slower query already has data', async () => {
838 const key1 = queryKey()
839 const key2 = queryKey()
840β
841 queryClient.setQueryData(key1, 'cached')
842β
843 function Page() {
844 const [result1, result2] = useSuspenseQueries({
845 queries: [
846 {
847 queryKey: key1,
848 queryFn: () => sleep(2000).then(() => 'data1'),
849 },
850 {
851 queryKey: key2,
852 queryFn: () => sleep(1000).then(() => 'data2'),
853 },
854 ],
855 })
856β
857 return (
858 <div>
859 <div>data1: {result1.data}</div>
860 <div>data2: {result2.data}</div>
861 </div>
862 )
863 }
864β
865 const rendered = renderWithClient(
866 queryClient,
867 <React.Suspense fallback={<div>loading</div>}>
868 <Page />
869 </React.Suspense>,
870 )
871β
872 expect(rendered.getByText('loading')).toBeInTheDocument()
873β
874 // key2 resolves: suspend lifts, key1 shows cached data, key2 shows fresh data
875 await act(() => vi.advanceTimersByTimeAsync(1000))
876β
877 expect(rendered.getByText('data1: cached')).toBeInTheDocument()
878 expect(rendered.getByText('data2: data2')).toBeInTheDocument()
879β
880 // key1 stale timer fires, triggering background refetch
881 await act(() => vi.advanceTimersByTimeAsync(1000))
882β
883 // key1 background refetch completes: key1 updates to fresh data
884 await act(() => vi.advanceTimersByTimeAsync(2000))
885β
886 expect(rendered.getByText('data1: data1')).toBeInTheDocument()
887 expect(rendered.getByText('data2: data2')).toBeInTheDocument()
888 })
889β
890 it('should only suspend queries that are pending when the faster query already has data', async () => {
891 const key1 = queryKey()
892 const key2 = queryKey()
893β
894 queryClient.setQueryData(key2, 'cached')
895β
896 function Page() {
897 const [result1, result2] = useSuspenseQueries({
898 queries: [
899 {
900 queryKey: key1,
901 queryFn: () => sleep(2000).then(() => 'data1'),
902 },
903 {
904 queryKey: key2,
905 queryFn: () => sleep(1000).then(() => 'data2'),
906 },
907 ],
908 })
909β
910 return (
911 <div>
912 <div>data1: {result1.data}</div>
913 <div>data2: {result2.data}</div>
914 </div>
915 )
916 }
917β
918 const rendered = renderWithClient(
919 queryClient,
920 <React.Suspense fallback={<div>loading</div>}>
921 <Page />
922 </React.Suspense>,
923 )
924β
925 expect(rendered.getByText('loading')).toBeInTheDocument()
926β
927 // key1 resolves: suspend lifts, key1 shows fresh data, key2 shows cached data
928 await act(() => vi.advanceTimersByTimeAsync(2000))
929β
930 expect(rendered.getByText('data1: data1')).toBeInTheDocument()
931 expect(rendered.getByText('data2: cached')).toBeInTheDocument()
932β
933 // key2 stale timer fires, triggering background refetch
934 await act(() => vi.advanceTimersByTimeAsync(1000))
935β
936 // key2 background refetch completes: key2 updates to fresh data
937 await act(() => vi.advanceTimersByTimeAsync(1000))
938β
939 expect(rendered.getByText('data1: data1')).toBeInTheDocument()
940 expect(rendered.getByText('data2: data2')).toBeInTheDocument()
941 })
942β
943 it('should not suspend and not refetch when all queries have fresh cached data', () => {
944 const key1 = queryKey()
945 const key2 = queryKey()
946β
947 queryClient.setQueryData(key1, 'cached1')
948 queryClient.setQueryData(key2, 'cached2')
949β
950 const queryFn1 = vi.fn(() => sleep(20).then(() => 'data1'))
951 const queryFn2 = vi.fn(() => sleep(10).then(() => 'data2'))
952β
953 function Page() {
954 const [result1, result2] = useSuspenseQueries({
955 queries: [
956 {
957 queryKey: key1,
958 queryFn: queryFn1,
959 },
960 {
961 queryKey: key2,
962 queryFn: queryFn2,
963 },
964 ],
965 })
966β
967 return (
968 <div>
969 <div>data1: {result1.data}</div>
970 <div>data2: {result2.data}</div>
971 </div>
972 )
973 }
974β
975 const rendered = renderWithClient(
976 queryClient,
977 <React.Suspense fallback={<div>loading</div>}>
978 <Page />
979 </React.Suspense>,
980 )
981β
982 // No suspend, fresh cached data shown immediately
983 expect(rendered.getByText('data1: cached1')).toBeInTheDocument()
984 expect(rendered.getByText('data2: cached2')).toBeInTheDocument()
985β
986 // No background refetch because data is still fresh (within staleTime)
987 expect(queryFn1).toHaveBeenCalledTimes(0)
988 expect(queryFn2).toHaveBeenCalledTimes(0)
989 })
990β
991 it('should not suspend but refetch when all queries have stale cached data', async () => {
992 const key1 = queryKey()
993 const key2 = queryKey()
994β
995 queryClient.setQueryData(key1, 'cached1')
996 queryClient.setQueryData(key2, 'cached2')
997β
998 // Advance past staleTime (min 1000ms in suspense) so data becomes stale before mount
999 vi.advanceTimersByTime(1000)
1000β
1001 function Page() {
1002 const [result1, result2] = useSuspenseQueries({
1003 queries: [
1004 {
1005 queryKey: key1,
1006 queryFn: () => sleep(20).then(() => 'data1'),
1007 },
1008 {
1009 queryKey: key2,
1010 queryFn: () => sleep(10).then(() => 'data2'),
1011 },
1012 ],
1013 })
1014β
1015 return (
1016 <div>
1017 <div>data1: {result1.data}</div>
1018 <div>data2: {result2.data}</div>
1019 </div>
1020 )
1021 }
1022β
1023 const rendered = renderWithClient(
1024 queryClient,
1025 <React.Suspense fallback={<div>loading</div>}>
1026 <Page />
1027 </React.Suspense>,
1028 )
1029β
1030 // No suspend, stale cached data shown immediately with background refetch started
1031 expect(rendered.getByText('data1: cached1')).toBeInTheDocument()
1032 expect(rendered.getByText('data2: cached2')).toBeInTheDocument()
1033β
1034 // key2 background refetch completes
1035 await act(() => vi.advanceTimersByTimeAsync(11))
1036β
1037 expect(rendered.getByText('data1: cached1')).toBeInTheDocument()
1038 expect(rendered.getByText('data2: data2')).toBeInTheDocument()
1039β
1040 // key1 background refetch completes
1041 await act(() => vi.advanceTimersByTimeAsync(10))
1042β
1043 expect(rendered.getByText('data1: data1')).toBeInTheDocument()
1044 expect(rendered.getByText('data2: data2')).toBeInTheDocument()
1045 })
1046})