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