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 queryClient.clear()
38 onSuspend.mockClear()
39 onQueriesResolution.mockClear()
40 vi.useRealTimers()
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 a queryFn rejects with a falsy error', async () => {
527 const consoleMock = vi
528 .spyOn(console, 'error')
529 .mockImplementation(() => undefined)
530 const key = queryKey()
531β
532 function Page() {
533 const [query] = useSuspenseQueries({
534 queries: [
535 {
536 queryKey: key,
537 // Preact's error path dereferences the thrown value (`if (e.then)`), so a
538 // literal `undefined` error crashes the framework. `0` is just an arbitrary
539 // falsy value that's safe to dereference (`(0).then` is `undefined`, not a
540 // crash) β any falsy primitive other than `null`/`undefined` would do.
541 queryFn: () => sleep(10).then(() => Promise.reject(0)),
542 retry: false,
543 },
544 ],
545 })
546β
547 return <div>data: {String(query.data)}</div>
548 }
549β
550 const rendered = renderWithClient(
551 queryClient,
552 <ErrorBoundary fallbackRender={() => <div>error boundary</div>}>
553 <Suspense fallback="loading">
554 <Page />
555 </Suspense>
556 </ErrorBoundary>,
557 )
558β
559 expect(rendered.getByText('loading')).toBeInTheDocument()
560β
561 await vi.advanceTimersByTimeAsync(10)
562 expect(rendered.getByText('error boundary')).toBeInTheDocument()
563 consoleMock.mockRestore()
564 })
565β
566 it('should throw error when queryKey changes and new query fails', async () => {
567 const consoleMock = vi
568 .spyOn(console, 'error')
569 .mockImplementation(() => undefined)
570 const key = queryKey()
571β
572 function Page({ fail }: { fail: boolean }) {
573 const { data } = useSuspenseQuery({
574 queryKey: [key, fail],
575 queryFn: () =>
576 sleep(10).then(() => {
577 if (fail) throw new Error('Suspense Error Bingo')
578 return 'data'
579 }),
580 retry: 0,
581 })
582β
583 return <div>rendered: {data}</div>
584 }
585β
586 function TestApp() {
587 const [fail, setFail] = useState(false)
588β
589 return (
590 <>
591 <button onClick={() => setFail(true)}>trigger fail</button>
592 <ErrorBoundary fallbackRender={() => <div>error boundary</div>}>
593 <Suspense fallback="loading">
594 <Page fail={fail} />
595 </Suspense>
596 </ErrorBoundary>
597 </>
598 )
599 }
600β
601 const rendered = renderWithClient(queryClient, <TestApp />)
602β
603 expect(rendered.getByText('loading')).toBeInTheDocument()
604 await vi.advanceTimersByTimeAsync(10)
605 expect(rendered.getByText('rendered: data')).toBeInTheDocument()
606β
607 fireEvent.click(rendered.getByText('trigger fail'))
608 expect(rendered.getByText('loading')).toBeInTheDocument()
609 await vi.advanceTimersByTimeAsync(10)
610 expect(rendered.getByText('error boundary')).toBeInTheDocument()
611β
612 expect(consoleMock.mock.calls[0]?.[1]).toStrictEqual(
613 new Error('Suspense Error Bingo'),
614 )
615β
616 consoleMock.mockRestore()
617 })
618β
619 it('should keep previous data when wrapped in a transition', async () => {
620 const key = queryKey()
621β
622 function Page({ count, isPending }: { count: number; isPending: boolean }) {
623 const { data } = useSuspenseQuery({
624 queryKey: [key, count],
625 queryFn: () => sleep(10).then(() => `data${count}`),
626 })
627β
628 return <div>{isPending ? 'pending' : data}</div>
629 }
630β
631 function TestApp() {
632 const [count, setCount] = useState(0)
633 const [isPending, startTransition] = useTransition()
634β
635 return (
636 <>
637 <button onClick={() => startTransition(() => setCount((c) => c + 1))}>
638 inc
639 </button>
640 <Suspense fallback="loading">
641 <Page count={count} isPending={isPending} />
642 </Suspense>
643 </>
644 )
645 }
646β
647 const rendered = renderWithClient(queryClient, <TestApp />)
648β
649 expect(rendered.getByText('loading')).toBeInTheDocument()
650 await vi.advanceTimersByTimeAsync(10)
651 expect(rendered.getByText('data0')).toBeInTheDocument()
652β
653 fireEvent.click(rendered.getByText('inc'))
654 // Expect no concurrent updates in Preact
655 expect(rendered.getByText('loading')).toBeInTheDocument()
656 await vi.advanceTimersByTimeAsync(10)
657 expect(rendered.getByText('data1')).toBeInTheDocument()
658 })
659β
660 it('should not request old data inside transitions (issue #6486)', async () => {
661 const key = queryKey()
662 let queryFnCount = 0
663β
664 function App() {
665 const [count, setCount] = useState(0)
666β
667 return (
668 <div>
669 <button onClick={() => startTransition(() => setCount(count + 1))}>
670 inc
671 </button>
672 <Suspense fallback="loading">
673 <Page count={count} />
674 </Suspense>
675 </div>
676 )
677 }
678β
679 function Page({ count }: { count: number }) {
680 const { data } = useSuspenseQuery({
681 queryKey: [key, count],
682 queryFn: () =>
683 sleep(10).then(() => {
684 queryFnCount++
685 return `data${count}`
686 }),
687 })
688β
689 return (
690 <div>
691 <div>{String(data)}</div>
692 </div>
693 )
694 }
695β
696 const rendered = renderWithClient(
697 queryClient,
698β
699 <App />,
700 )
701β
702 expect(rendered.getByText('loading')).toBeInTheDocument()
703 await vi.advanceTimersByTimeAsync(10)
704 expect(rendered.getByText('data0')).toBeInTheDocument()
705β
706 fireEvent.click(rendered.getByText('inc'))
707 await vi.advanceTimersByTimeAsync(10)
708 expect(rendered.getByText('data1')).toBeInTheDocument()
709β
710 expect(queryFnCount).toBe(2)
711 })
712β
713 it('should still suspense if queryClient has placeholderData config', async () => {
714 const key = queryKey()
715 const queryClientWithPlaceholder = new QueryClient({
716 defaultOptions: {
717 queries: {
718 placeholderData: (previousData: any) => previousData,
719 },
720 },
721 })
722β
723 function Page({ count, isPending }: { count: number; isPending: boolean }) {
724 const { data } = useSuspenseQuery({
725 queryKey: [key, count],
726 queryFn: () => sleep(10).then(() => `data${count}`),
727 })
728β
729 return (
730 <div>
731 <div>{isPending ? 'pending' : data}</div>
732 </div>
733 )
734 }
735β
736 function TestApp() {
737 const [count, setCount] = useState(0)
738 const [isPending, startTransition] = useTransition()
739β
740 return (
741 <>
742 <button onClick={() => startTransition(() => setCount((c) => c + 1))}>
743 inc
744 </button>
745 <Suspense fallback="loading">
746 <Page count={count} isPending={isPending} />
747 </Suspense>
748 </>
749 )
750 }
751β
752 const rendered = renderWithClient(queryClientWithPlaceholder, <TestApp />)
753β
754 expect(rendered.getByText('loading')).toBeInTheDocument()
755 await act(async () => {
756 await vi.advanceTimersByTimeAsync(10)
757 })
758 expect(rendered.getByText('data0')).toBeInTheDocument()
759β
760 fireEvent.click(rendered.getByText('inc'))
761 expect(rendered.getByText('loading')).toBeInTheDocument()
762 await act(async () => {
763 await vi.advanceTimersByTimeAsync(10)
764 })
765 expect(rendered.getByText('data1')).toBeInTheDocument()
766 })
767β
768 it('should show error boundary even with gcTime:0 (#7853)', async () => {
769 const consoleMock = vi
770 .spyOn(console, 'error')
771 .mockImplementation(() => undefined)
772 const key = queryKey()
773 let count = 0
774β
775 function Page() {
776 useSuspenseQuery({
777 queryKey: key,
778 queryFn: () =>
779 sleep(10).then(() => {
780 count++
781 throw new Error('Query failed')
782 }),
783 gcTime: 0,
784 retry: false,
785 })
786β
787 return null
788 }
789β
790 function App() {
791 return (
792 <Suspense fallback="loading">
793 <ErrorBoundary
794 fallbackRender={() => {
795 return <div>There was an error!</div>
796 }}
797 >
798 <Page />
799 </ErrorBoundary>
800 </Suspense>
801 )
802 }
803β
804 const rendered = renderWithClient(queryClient, <App />)
805β
806 expect(rendered.getByText('loading')).toBeInTheDocument()
807 await vi.advanceTimersByTimeAsync(10)
808 expect(rendered.getByText('There was an error!')).toBeInTheDocument()
809β
810 expect(count).toBe(1)
811β
812 consoleMock.mockRestore()
813 })
814β
815 describe('gc (with fake timers)', () => {
816 beforeAll(() => {
817 vi.useFakeTimers()
818 })
819β
820 afterAll(() => {
821 vi.useRealTimers()
822 })
823β
824 it('should gc when unmounted while fetching with low gcTime (#8159)', async () => {
825 const key = queryKey()
826β
827 function Page() {
828 return (
829 <Suspense fallback="loading">
830 <Component />
831 </Suspense>
832 )
833 }
834β
835 function Component() {
836 const { data } = useSuspenseQuery({
837 queryKey: key,
838 queryFn: () => sleep(3000).then(() => 'data'),
839 gcTime: 1000,
840 })
841β
842 return <div>{data}</div>
843 }
844β
845 function Page2() {
846 return <div>page2</div>
847 }
848β
849 function App() {
850 const [show, setShow] = useState(true)
851β
852 return (
853 <div>
854 {show ? <Page /> : <Page2 />}
855 <button onClick={() => setShow(false)}>hide</button>
856 </div>
857 )
858 }
859β
860 const rendered = renderWithClient(queryClient, <App />)
861β
862 expect(rendered.getByText('loading')).toBeInTheDocument()
863β
864 fireEvent.click(rendered.getByText('hide'))
865 expect(rendered.getByText('page2')).toBeInTheDocument()
866 // wait for query to be resolved
867 await vi.advanceTimersByTimeAsync(3000)
868 expect(queryClient.getQueryData(key)).toBe('data')
869 // wait for gc
870 await vi.advanceTimersByTimeAsync(1000)
871 expect(queryClient.getQueryData(key)).toBe(undefined)
872 })
873 })
874β
875 it('should log an error when skipToken is passed as queryFn', () => {
876 const consoleErrorSpy = vi
877 .spyOn(console, 'error')
878 .mockImplementation(() => {})
879 const key = queryKey()
880β
881 function Page() {
882 useSuspenseQueries({
883 queries: [
884 {
885 queryKey: key,
886 // @ts-expect-error
887 queryFn: Math.random() >= 0 ? skipToken : () => Promise.resolve(5),
888 },
889 ],
890 })
891β
892 return null
893 }
894β
895 function App() {
896 return (
897 <Suspense fallback="loading">
898 <Page />
899 </Suspense>
900 )
901 }
902β
903 renderWithClient(queryClient, <App />)
904β
905 expect(consoleErrorSpy).toHaveBeenCalledWith(
906 'skipToken is not allowed for useSuspenseQueries',
907 )
908 consoleErrorSpy.mockRestore()
909 })
910β
911 it('should log an error when skipToken is used in development environment', () => {
912 const envCopy = process.env.NODE_ENV
913 process.env.NODE_ENV = 'development'
914β
915 const consoleErrorSpy = vi
916 .spyOn(console, 'error')
917 .mockImplementation(() => undefined)
918 const key = queryKey()
919β
920 function Page() {
921 useSuspenseQueries({
922 queries: [
923 {
924 queryKey: key,
925 queryFn: skipToken as any,
926 },
927 ],
928 })
929β
930 return null
931 }
932β
933 renderWithClient(
934 queryClient,
935 <Suspense fallback="loading">
936 <Page />
937 </Suspense>,
938 )
939β
940 expect(consoleErrorSpy).toHaveBeenCalledWith(
941 'skipToken is not allowed for useSuspenseQueries',
942 )
943 consoleErrorSpy.mockRestore()
944 process.env.NODE_ENV = envCopy
945 })
946β
947 it('should not log an error when skipToken is used in production environment', () => {
948 const envCopy = process.env.NODE_ENV
949 process.env.NODE_ENV = 'production'
950β
951 const consoleErrorSpy = vi
952 .spyOn(console, 'error')
953 .mockImplementation(() => undefined)
954 const key = queryKey()
955β
956 function Page() {
957 useSuspenseQueries({
958 queries: [
959 {
960 queryKey: key,
961 queryFn: skipToken as any,
962 },
963 ],
964 })
965β
966 return null
967 }
968β
969 renderWithClient(
970 queryClient,
971 <Suspense fallback="loading">
972 <Page />
973 </Suspense>,
974 )
975β
976 expect(consoleErrorSpy).not.toHaveBeenCalled()
977 consoleErrorSpy.mockRestore()
978 process.env.NODE_ENV = envCopy
979 })
980β
981 it('should only suspend queries that are pending when the slower query already has data', async () => {
982 const key1 = queryKey()
983 const key2 = queryKey()
984β
985 queryClient.setQueryData(key1, 'cached')
986β
987 function Page() {
988 const [result1, result2] = useSuspenseQueries({
989 queries: [
990 {
991 queryKey: key1,
992 queryFn: () => sleep(2000).then(() => 'data1'),
993 },
994 {
995 queryKey: key2,
996 queryFn: () => sleep(1000).then(() => 'data2'),
997 },
998 ],
999 })
1000β
1001 return (
1002 <div>
1003 <div>data1: {result1.data}</div>
1004 <div>data2: {result2.data}</div>
1005 </div>
1006 )
1007 }
1008β
1009 const rendered = renderWithClient(
1010 queryClient,
1011 <Suspense fallback={<div>loading</div>}>
1012 <Page />
1013 </Suspense>,
1014 )
1015β
1016 expect(rendered.getByText('loading')).toBeInTheDocument()
1017β
1018 // key2 resolves: suspend lifts, key1 shows cached data, key2 shows fresh data
1019 await vi.advanceTimersByTimeAsync(1000)
1020β
1021 expect(rendered.getByText('data1: cached')).toBeInTheDocument()
1022 expect(rendered.getByText('data2: data2')).toBeInTheDocument()
1023β
1024 // key1 stale timer fires, triggering background refetch
1025 await vi.advanceTimersByTimeAsync(1000)
1026β
1027 // key1 background refetch completes: key1 updates to fresh data
1028 await vi.advanceTimersByTimeAsync(2000)
1029β
1030 expect(rendered.getByText('data1: data1')).toBeInTheDocument()
1031 expect(rendered.getByText('data2: data2')).toBeInTheDocument()
1032 })
1033β
1034 it('should only suspend queries that are pending when the faster query already has data', async () => {
1035 const key1 = queryKey()
1036 const key2 = queryKey()
1037β
1038 queryClient.setQueryData(key2, 'cached')
1039β
1040 function Page() {
1041 const [result1, result2] = useSuspenseQueries({
1042 queries: [
1043 {
1044 queryKey: key1,
1045 queryFn: () => sleep(2000).then(() => 'data1'),
1046 },
1047 {
1048 queryKey: key2,
1049 queryFn: () => sleep(1000).then(() => 'data2'),
1050 },
1051 ],
1052 })
1053β
1054 return (
1055 <div>
1056 <div>data1: {result1.data}</div>
1057 <div>data2: {result2.data}</div>
1058 </div>
1059 )
1060 }
1061β
1062 const rendered = renderWithClient(
1063 queryClient,
1064 <Suspense fallback={<div>loading</div>}>
1065 <Page />
1066 </Suspense>,
1067 )
1068β
1069 expect(rendered.getByText('loading')).toBeInTheDocument()
1070β
1071 // key1 resolves: suspend lifts, key1 shows fresh data, key2 shows cached data
1072 await vi.advanceTimersByTimeAsync(2000)
1073β
1074 expect(rendered.getByText('data1: data1')).toBeInTheDocument()
1075 expect(rendered.getByText('data2: cached')).toBeInTheDocument()
1076β
1077 // key2 stale timer fires, triggering background refetch
1078 await vi.advanceTimersByTimeAsync(1000)
1079β
1080 // key2 background refetch completes: key2 updates to fresh data
1081 await vi.advanceTimersByTimeAsync(1000)
1082β
1083 expect(rendered.getByText('data1: data1')).toBeInTheDocument()
1084 expect(rendered.getByText('data2: data2')).toBeInTheDocument()
1085 })
1086β
1087 it('should not suspend and not refetch when all queries have fresh cached data', () => {
1088 const key1 = queryKey()
1089 const key2 = queryKey()
1090β
1091 queryClient.setQueryData(key1, 'cached1')
1092 queryClient.setQueryData(key2, 'cached2')
1093β
1094 const queryFn1 = vi.fn(() => sleep(20).then(() => 'data1'))
1095 const queryFn2 = vi.fn(() => sleep(10).then(() => 'data2'))
1096β
1097 function Page() {
1098 const [result1, result2] = useSuspenseQueries({
1099 queries: [
1100 {
1101 queryKey: key1,
1102 queryFn: queryFn1,
1103 },
1104 {
1105 queryKey: key2,
1106 queryFn: queryFn2,
1107 },
1108 ],
1109 })
1110β
1111 return (
1112 <div>
1113 <div>data1: {result1.data}</div>
1114 <div>data2: {result2.data}</div>
1115 </div>
1116 )
1117 }
1118β
1119 const rendered = renderWithClient(
1120 queryClient,
1121 <Suspense fallback={<div>loading</div>}>
1122 <Page />
1123 </Suspense>,
1124 )
1125β
1126 // No suspend, fresh cached data shown immediately
1127 expect(rendered.getByText('data1: cached1')).toBeInTheDocument()
1128 expect(rendered.getByText('data2: cached2')).toBeInTheDocument()
1129β
1130 // No background refetch because data is still fresh (within staleTime)
1131 expect(queryFn1).toHaveBeenCalledTimes(0)
1132 expect(queryFn2).toHaveBeenCalledTimes(0)
1133 })
1134β
1135 it('should not suspend and only refetch the stale query when one query has fresh and the other has stale cached data', async () => {
1136 const key1 = queryKey()
1137 const key2 = queryKey()
1138β
1139 queryClient.setQueryData(key1, 'cached1')
1140 queryClient.setQueryData(key2, 'cached2')
1141β
1142 // Advance past staleTime (min 1000ms in suspense) so key2 becomes stale before mount
1143 vi.advanceTimersByTime(1000)
1144β
1145 // Make key1 fresh again by resetting its data
1146 queryClient.setQueryData(key1, 'cached1')
1147β
1148 const queryFn1 = vi.fn(() => sleep(20).then(() => 'data1'))
1149β
1150 function Page() {
1151 const [result1, result2] = useSuspenseQueries({
1152 queries: [
1153 {
1154 queryKey: key1,
1155 queryFn: queryFn1,
1156 },
1157 {
1158 queryKey: key2,
1159 queryFn: () => sleep(10).then(() => 'data2'),
1160 },
1161 ],
1162 })
1163β
1164 return (
1165 <div>
1166 <div>data1: {result1.data}</div>
1167 <div>data2: {result2.data}</div>
1168 </div>
1169 )
1170 }
1171β
1172 const rendered = renderWithClient(
1173 queryClient,
1174 <Suspense fallback={<div>loading</div>}>
1175 <Page />
1176 </Suspense>,
1177 )
1178β
1179 // No suspend, cached data shown immediately
1180 expect(rendered.getByText('data1: cached1')).toBeInTheDocument()
1181 expect(rendered.getByText('data2: cached2')).toBeInTheDocument()
1182β
1183 // key1 is fresh, no refetch
1184 expect(queryFn1).toHaveBeenCalledTimes(0)
1185β
1186 // key2 background refetch completes
1187 await vi.advanceTimersByTimeAsync(11)
1188β
1189 expect(rendered.getByText('data1: cached1')).toBeInTheDocument()
1190 expect(rendered.getByText('data2: data2')).toBeInTheDocument()
1191β
1192 // key1 is still fresh, no refetch triggered
1193 expect(queryFn1).toHaveBeenCalledTimes(0)
1194β
1195 // after key2 refetch completes, key1 is still fresh with no refetch triggered
1196 await vi.advanceTimersByTimeAsync(10)
1197β
1198 expect(rendered.getByText('data1: cached1')).toBeInTheDocument()
1199 expect(rendered.getByText('data2: data2')).toBeInTheDocument()
1200 expect(queryFn1).toHaveBeenCalledTimes(0)
1201 })
1202β
1203 it('should not suspend and only refetch the stale query when one query has stale and the other has fresh cached data', async () => {
1204 const key1 = queryKey()
1205 const key2 = queryKey()
1206β
1207 queryClient.setQueryData(key1, 'cached1')
1208 queryClient.setQueryData(key2, 'cached2')
1209β
1210 // Advance past staleTime (min 1000ms in suspense) so key1 becomes stale before mount
1211 vi.advanceTimersByTime(1000)
1212β
1213 // Make key2 fresh again by resetting its data
1214 queryClient.setQueryData(key2, 'cached2')
1215β
1216 const queryFn2 = vi.fn(() => sleep(20).then(() => 'data2'))
1217β
1218 function Page() {
1219 const [result1, result2] = useSuspenseQueries({
1220 queries: [
1221 {
1222 queryKey: key1,
1223 queryFn: () => sleep(10).then(() => 'data1'),
1224 },
1225 {
1226 queryKey: key2,
1227 queryFn: queryFn2,
1228 },
1229 ],
1230 })
1231β
1232 return (
1233 <div>
1234 <div>data1: {result1.data}</div>
1235 <div>data2: {result2.data}</div>
1236 </div>
1237 )
1238 }
1239β
1240 const rendered = renderWithClient(
1241 queryClient,
1242 <Suspense fallback={<div>loading</div>}>
1243 <Page />
1244 </Suspense>,
1245 )
1246β
1247 // No suspend, cached data shown immediately
1248 expect(rendered.getByText('data1: cached1')).toBeInTheDocument()
1249 expect(rendered.getByText('data2: cached2')).toBeInTheDocument()
1250β
1251 // key2 is fresh, no refetch
1252 expect(queryFn2).toHaveBeenCalledTimes(0)
1253β
1254 // key1 background refetch completes
1255 await vi.advanceTimersByTimeAsync(11)
1256β
1257 expect(rendered.getByText('data1: data1')).toBeInTheDocument()
1258 expect(rendered.getByText('data2: cached2')).toBeInTheDocument()
1259β
1260 // key2 is still fresh, no refetch triggered
1261 expect(queryFn2).toHaveBeenCalledTimes(0)
1262β
1263 // after key1 refetch completes, key2 is still fresh with no refetch triggered
1264 await vi.advanceTimersByTimeAsync(10)
1265β
1266 expect(rendered.getByText('data1: data1')).toBeInTheDocument()
1267 expect(rendered.getByText('data2: cached2')).toBeInTheDocument()
1268 expect(queryFn2).toHaveBeenCalledTimes(0)
1269 })
1270β
1271 it('should not suspend but refetch when all queries have stale cached data', async () => {
1272 const key1 = queryKey()
1273 const key2 = queryKey()
1274β
1275 queryClient.setQueryData(key1, 'cached1')
1276 queryClient.setQueryData(key2, 'cached2')
1277β
1278 // Advance past staleTime (min 1000ms in suspense) so data becomes stale before mount
1279 vi.advanceTimersByTime(1000)
1280β
1281 function Page() {
1282 const [result1, result2] = useSuspenseQueries({
1283 queries: [
1284 {
1285 queryKey: key1,
1286 queryFn: () => sleep(20).then(() => 'data1'),
1287 },
1288 {
1289 queryKey: key2,
1290 queryFn: () => sleep(10).then(() => 'data2'),
1291 },
1292 ],
1293 })
1294β
1295 return (
1296 <div>
1297 <div>data1: {result1.data}</div>
1298 <div>data2: {result2.data}</div>
1299 </div>
1300 )
1301 }
1302β
1303 const rendered = renderWithClient(
1304 queryClient,
1305 <Suspense fallback={<div>loading</div>}>
1306 <Page />
1307 </Suspense>,
1308 )
1309β
1310 // No suspend, stale cached data shown immediately with background refetch started
1311 expect(rendered.getByText('data1: cached1')).toBeInTheDocument()
1312 expect(rendered.getByText('data2: cached2')).toBeInTheDocument()
1313β
1314 // key2 background refetch completes
1315 await vi.advanceTimersByTimeAsync(11)
1316β
1317 expect(rendered.getByText('data1: cached1')).toBeInTheDocument()
1318 expect(rendered.getByText('data2: data2')).toBeInTheDocument()
1319β
1320 // key1 background refetch completes
1321 await vi.advanceTimersByTimeAsync(10)
1322β
1323 expect(rendered.getByText('data1: data1')).toBeInTheDocument()
1324 expect(rendered.getByText('data2: data2')).toBeInTheDocument()
1325 })
1326})