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