Open History to see the last commit
1import {
2 afterAll,
3 afterEach,
4 beforeAll,
5 describe,
6 expect,
7 it,
8 vi,
9} from 'vitest'
10import { act, fireEvent, render, waitFor } from '@testing-library/react'
11import * as React from 'react'
12import { ErrorBoundary } from 'react-error-boundary'
13import { queryKey, sleep } from '@tanstack/query-test-utils'
14import {
15 QueryClient,
16 skipToken,
17 useSuspenseQueries,
18 useSuspenseQuery,
19} from '..'
20import { renderWithClient } from './utils'
21import type { UseSuspenseQueryOptions } from '..'
22β
23type NumberQueryOptions = UseSuspenseQueryOptions<number>
24β
25const QUERY_DURATION = 1000
26β
27const createQuery: (id: number) => NumberQueryOptions = (id) => ({
28 queryKey: [id],
29 queryFn: async () => {
30 await sleep(QUERY_DURATION)
31 return id
32 },
33})
34const resolveQueries = () => vi.advanceTimersByTimeAsync(QUERY_DURATION)
35β
36const queryClient = new QueryClient()
37β
38describe('useSuspenseQueries', () => {
39 const onSuspend = vi.fn()
40 const onQueriesResolution = vi.fn()
41β
42 beforeAll(() => {
43 vi.useFakeTimers()
44 })
45β
46 afterAll(() => {
47 vi.useRealTimers()
48 })
49β
50 afterEach(() => {
51 queryClient.clear()
52 onSuspend.mockClear()
53 onQueriesResolution.mockClear()
54 })
55β
56 function SuspenseFallback() {
57 React.useEffect(() => {
58 onSuspend()
59 }, [])
60β
61 return null
62 }
63β
64 const withSuspenseWrapper = <T extends object>(Component: React.FC<T>) => {
65 function SuspendedComponent(props: T) {
66 return (
67 <React.Suspense fallback={<SuspenseFallback />}>
68 <Component {...props} />
69 </React.Suspense>
70 )
71 }
72β
73 return SuspendedComponent
74 }
75β
76 function QueriesContainer({
77 queries,
78 }: {
79 queries: Array<NumberQueryOptions>
80 }) {
81 const queriesResults = useSuspenseQueries(
82 { queries, combine: (results) => results.map((r) => r.data) },
83 queryClient,
84 )
85β
86 React.useEffect(() => {
87 onQueriesResolution(queriesResults)
88 }, [queriesResults])
89β
90 return null
91 }
92β
93 const TestComponent = withSuspenseWrapper(QueriesContainer)
94β
95 it('should suspend on mount', () => {
96 render(<TestComponent queries={[1, 2].map(createQuery)} />)
97β
98 expect(onSuspend).toHaveBeenCalledOnce()
99 })
100β
101 it('should resolve queries', async () => {
102 render(<TestComponent queries={[1, 2].map(createQuery)} />)
103β
104 await act(resolveQueries)
105β
106 expect(onQueriesResolution).toHaveBeenCalledTimes(1)
107 expect(onQueriesResolution).toHaveBeenLastCalledWith([1, 2])
108 })
109β
110 it('should not suspend on mount if query has been already fetched', () => {
111 const query = createQuery(1)
112β
113 queryClient.setQueryData(query.queryKey, query.queryFn)
114β
115 render(<TestComponent queries={[query]} />)
116β
117 expect(onSuspend).not.toHaveBeenCalled()
118 })
119β
120 it('should not break suspense when queries change without resolving', async () => {
121 const initQueries = [1, 2].map(createQuery)
122 const nextQueries = [3, 4, 5, 6].map(createQuery)
123β
124 const { rerender } = render(<TestComponent queries={initQueries} />)
125β
126 rerender(<TestComponent queries={nextQueries} />)
127β
128 await act(resolveQueries)
129β
130 expect(onSuspend).toHaveBeenCalledTimes(1)
131 expect(onQueriesResolution).toHaveBeenCalledTimes(1)
132 expect(onQueriesResolution).toHaveBeenLastCalledWith([3, 4, 5, 6])
133 })
134β
135 it('should suspend only once per queries change', async () => {
136 const initQueries = [1, 2].map(createQuery)
137 const nextQueries = [3, 4, 5, 6].map(createQuery)
138β
139 const { rerender } = render(<TestComponent queries={initQueries} />)
140β
141 await act(resolveQueries)
142β
143 rerender(<TestComponent queries={nextQueries} />)
144β
145 await act(resolveQueries)
146β
147 expect(onSuspend).toHaveBeenCalledTimes(2)
148 expect(onQueriesResolution).toHaveBeenCalledTimes(2)
149 expect(onQueriesResolution).toHaveBeenLastCalledWith([3, 4, 5, 6])
150 })
151β
152 it('should only call combine after resolving', async () => {
153 const spy = vi.fn()
154 const key = queryKey()
155β
156 function Page() {
157 const data = useSuspenseQueries({
158 queries: [1, 2, 3].map((value) => ({
159 queryKey: [...key, { value }],
160 queryFn: async () => {
161 await sleep(value * 10)
162 return { value: value * 10 }
163 },
164 })),
165 combine: (result) => {
166 spy(result)
167 return 'data'
168 },
169 })
170β
171 return <h1>{data}</h1>
172 }
173β
174 const rendered = renderWithClient(
175 queryClient,
176 <React.Suspense fallback="loading...">
177 <Page />
178 </React.Suspense>,
179 )
180β
181 await act(() => vi.advanceTimersByTimeAsync(10))
182β
183 rendered.getByText('loading...')
184β
185 expect(spy).not.toHaveBeenCalled()
186β
187 await act(() => vi.advanceTimersByTimeAsync(30))
188 rendered.getByText('data')
189β
190 expect(spy).toHaveBeenCalled()
191 })
192})
193β
194describe('useSuspenseQueries 2', () => {
195 it('should suspend all queries in parallel', async () => {
196 const key1 = queryKey()
197 const key2 = queryKey()
198 const results: Array<string> = []
199β
200 function Fallback() {
201 results.push('loading')
202 return <div>loading</div>
203 }
204β
205 function Page() {
206 const result = useSuspenseQueries({
207 queries: [
208 {
209 queryKey: key1,
210 queryFn: async () => {
211 results.push('1')
212 await sleep(10)
213 return '1'
214 },
215 },
216 {
217 queryKey: key2,
218 queryFn: async () => {
219 results.push('2')
220 await sleep(20)
221 return '2'
222 },
223 },
224 ],
225 })
226 return (
227 <div>
228 <h1>data: {result.map((item) => item.data ?? 'null').join(',')}</h1>
229 </div>
230 )
231 }
232β
233 const rendered = renderWithClient(
234 queryClient,
235 <React.Suspense fallback={<Fallback />}>
236 <Page />
237 </React.Suspense>,
238 )
239β
240 await waitFor(() => rendered.getByText('loading'))
241 await waitFor(() => rendered.getByText('data: 1,2'))
242β
243 expect(results).toEqual(['1', '2', 'loading'])
244 })
245β
246 it("shouldn't unmount before all promises fetched", async () => {
247 const key1 = queryKey()
248 const key2 = queryKey()
249 const results: Array<string> = []
250 const refs: Array<number> = []
251β
252 function Fallback() {
253 results.push('loading')
254 return <div>loading</div>
255 }
256β
257 function Page() {
258 const ref = React.useRef(Math.random())
259 const result = useSuspenseQueries({
260 queries: [
261 {
262 queryKey: key1,
263 queryFn: async () => {
264 refs.push(ref.current)
265 results.push('1')
266 await sleep(10)
267 return '1'
268 },
269 },
270 {
271 queryKey: key2,
272 queryFn: async () => {
273 refs.push(ref.current)
274 results.push('2')
275 await sleep(20)
276 return '2'
277 },
278 },
279 ],
280 })
281 return (
282 <div>
283 <h1>data: {result.map((item) => item.data ?? 'null').join(',')}</h1>
284 </div>
285 )
286 }
287β
288 const rendered = renderWithClient(
289 queryClient,
290 <React.Suspense fallback={<Fallback />}>
291 <Page />
292 </React.Suspense>,
293 )
294 await waitFor(() => rendered.getByText('loading'))
295 expect(refs.length).toBe(2)
296 await waitFor(() => rendered.getByText('data: 1,2'))
297 expect(refs[0]).toBe(refs[1])
298 })
299β
300 // this addresses the following issue:
301 // https://github.com/TanStack/query/issues/6344
302 it('should suspend on offline when query changes, and data should not be undefined', async () => {
303 function Page() {
304 const [id, setId] = React.useState(0)
305β
306 const { data } = useSuspenseQuery({
307 queryKey: [id],
308 queryFn: () => Promise.resolve(`Data ${id}`),
309 })
310β
311 // defensive guard here
312 if (data === undefined) {
313 throw new Error('data cannot be undefined')
314 }
315β
316 return (
317 <>
318 <div>{data}</div>
319 <button onClick={() => setId(id + 1)}>fetch</button>
320 </>
321 )
322 }
323β
324 const rendered = renderWithClient(
325 queryClient,
326 <React.Suspense fallback={<div>loading</div>}>
327 <Page />
328 </React.Suspense>,
329 )
330β
331 await waitFor(() =>
332 expect(rendered.getByText('loading')).toBeInTheDocument(),
333 )
334 await waitFor(() => rendered.getByText('Data 0'))
335β
336 // go offline
337 document.dispatchEvent(new CustomEvent('offline'))
338β
339 fireEvent.click(rendered.getByText('fetch'))
340 await waitFor(() =>
341 expect(rendered.getByText('Data 0')).toBeInTheDocument(),
342 )
343β
344 // go back online
345 document.dispatchEvent(new CustomEvent('online'))
346 fireEvent.click(rendered.getByText('fetch'))
347β
348 // query should resume
349 await waitFor(() =>
350 expect(rendered.getByText('Data 1')).toBeInTheDocument(),
351 )
352 })
353β
354 it('should throw error when queryKey changes and new query fails', async () => {
355 const consoleMock = vi
356 .spyOn(console, 'error')
357 .mockImplementation(() => undefined)
358 const key = queryKey()
359β
360 function Page() {
361 const [fail, setFail] = React.useState(false)
362 const { data } = useSuspenseQuery({
363 queryKey: [key, fail],
364 queryFn: async () => {
365 await sleep(10)
366β
367 if (fail) {
368 throw new Error('Suspense Error Bingo')
369 } else {
370 return 'data'
371 }
372 },
373 retry: 0,
374 })
375β
376 return (
377 <div>
378 <button onClick={() => setFail(true)}>trigger fail</button>
379β
380 <div>rendered: {String(data)}</div>
381 </div>
382 )
383 }
384β
385 const rendered = renderWithClient(
386 queryClient,
387 <ErrorBoundary fallbackRender={() => <div>error boundary</div>}>
388 <React.Suspense fallback={'Loading...'}>
389 <Page />
390 </React.Suspense>
391 </ErrorBoundary>,
392 )
393β
394 await waitFor(() => rendered.getByText('Loading...'))
395β
396 await waitFor(() => rendered.getByText('rendered: data'))
397β
398 fireEvent.click(rendered.getByText('trigger fail'))
399β
400 await waitFor(() => rendered.getByText('error boundary'))
401β
402 expect(consoleMock.mock.calls[0]?.[1]).toStrictEqual(
403 new Error('Suspense Error Bingo'),
404 )
405β
406 consoleMock.mockRestore()
407 })
408β
409 it('should keep previous data when wrapped in a transition', async () => {
410 const key = queryKey()
411β
412 function Page() {
413 const [count, setCount] = React.useState(0)
414 const [isPending, startTransition] = React.useTransition()
415 const { data } = useSuspenseQuery({
416 queryKey: [key, count],
417 queryFn: async () => {
418 await sleep(10)
419 return 'data' + count
420 },
421 })
422β
423 return (
424 <div>
425 <button onClick={() => startTransition(() => setCount(count + 1))}>
426 inc
427 </button>
428β
429 <div>{isPending ? 'Pending...' : String(data)}</div>
430 </div>
431 )
432 }
433β
434 const rendered = renderWithClient(
435 queryClient,
436 <React.Suspense fallback={'Loading...'}>
437 <Page />
438 </React.Suspense>,
439 )
440β
441 await waitFor(() =>
442 expect(rendered.getByText('Loading...')).toBeInTheDocument(),
443 )
444β
445 await waitFor(() => expect(rendered.getByText('data0')).toBeInTheDocument())
446β
447 fireEvent.click(rendered.getByText('inc'))
448β
449 await waitFor(() =>
450 expect(rendered.getByText('Pending...')).toBeInTheDocument(),
451 )
452β
453 await waitFor(() => expect(rendered.getByText('data1')).toBeInTheDocument())
454 })
455β
456 it('should not request old data inside transitions (issue #6486)', async () => {
457 const key = queryKey()
458 let queryFnCount = 0
459β
460 function App() {
461 const [count, setCount] = React.useState(0)
462β
463 return (
464 <div>
465 <button
466 onClick={() => React.startTransition(() => setCount(count + 1))}
467 >
468 inc
469 </button>
470 <React.Suspense fallback={'Loading...'}>
471 <Page count={count} />
472 </React.Suspense>
473 </div>
474 )
475 }
476β
477 function Page({ count }: { count: number }) {
478 const { data } = useSuspenseQuery({
479 queryKey: [key, count],
480 queryFn: async () => {
481 queryFnCount++
482 await sleep(10)
483 return 'data' + count
484 },
485 })
486β
487 return (
488 <div>
489 <div>{String(data)}</div>
490 </div>
491 )
492 }
493β
494 const rendered = renderWithClient(
495 queryClient,
496β
497 <App />,
498 )
499β
500 await waitFor(() => rendered.getByText('Loading...'))
501β
502 await waitFor(() => rendered.getByText('data0'))
503β
504 fireEvent.click(rendered.getByText('inc'))
505β
506 await waitFor(() => rendered.getByText('data1'))
507β
508 await sleep(20)
509β
510 expect(queryFnCount).toBe(2)
511 })
512β
513 it('should still suspense if queryClient has placeholderData config', async () => {
514 const key = queryKey()
515 const queryClientWithPlaceholder = new QueryClient({
516 defaultOptions: {
517 queries: {
518 placeholderData: (previousData: any) => previousData,
519 },
520 },
521 })
522β
523 function Page() {
524 const [count, setCount] = React.useState(0)
525 const [isPending, startTransition] = React.useTransition()
526 const { data } = useSuspenseQuery({
527 queryKey: [key, count],
528 queryFn: async () => {
529 await sleep(10)
530 return 'data' + count
531 },
532 })
533β
534 return (
535 <div>
536 <button onClick={() => startTransition(() => setCount(count + 1))}>
537 inc
538 </button>
539β
540 <div>{isPending ? 'Pending...' : String(data)}</div>
541 </div>
542 )
543 }
544β
545 const rendered = renderWithClient(
546 queryClientWithPlaceholder,
547 <React.Suspense fallback={'Loading...'}>
548 <Page />
549 </React.Suspense>,
550 )
551β
552 await waitFor(() =>
553 expect(rendered.getByText('Loading...')).toBeInTheDocument(),
554 )
555β
556 await waitFor(() => expect(rendered.getByText('data0')).toBeInTheDocument())
557β
558 fireEvent.click(rendered.getByText('inc'))
559β
560 await waitFor(() =>
561 expect(rendered.getByText('Pending...')).toBeInTheDocument(),
562 )
563β
564 await waitFor(() => expect(rendered.getByText('data1')).toBeInTheDocument())
565 })
566β
567 it('should show error boundary even with gcTime:0 (#7853)', async () => {
568 const consoleMock = vi
569 .spyOn(console, 'error')
570 .mockImplementation(() => undefined)
571 const key = queryKey()
572 let count = 0
573β
574 function Page() {
575 useSuspenseQuery({
576 queryKey: key,
577 queryFn: () => {
578 count++
579 return Promise.reject(new Error('Query failed'))
580 },
581 gcTime: 0,
582 retry: false,
583 })
584β
585 return null
586 }
587β
588 function App() {
589 return (
590 <React.Suspense fallback="loading">
591 <ErrorBoundary
592 fallbackRender={() => {
593 return <div>There was an error!</div>
594 }}
595 >
596 <Page />
597 </ErrorBoundary>
598 </React.Suspense>
599 )
600 }
601β
602 const rendered = renderWithClient(queryClient, <App />)
603β
604 await waitFor(() => rendered.getByText('There was an error!'))
605 expect(count).toBe(1)
606 consoleMock.mockRestore()
607 })
608β
609 describe('gc (with fake timers)', () => {
610 beforeAll(() => {
611 vi.useFakeTimers()
612 })
613β
614 afterAll(() => {
615 vi.useRealTimers()
616 })
617β
618 it('should gc when unmounted while fetching with low gcTime (#8159)', async () => {
619 const key = queryKey()
620β
621 function Page() {
622 return (
623 <React.Suspense fallback="loading">
624 <Component />
625 </React.Suspense>
626 )
627 }
628β
629 function Component() {
630 const { data } = useSuspenseQuery({
631 queryKey: key,
632 queryFn: async () => {
633 await sleep(3000)
634 return 'data'
635 },
636 gcTime: 1000,
637 })
638β
639 return <div>{data}</div>
640 }
641β
642 function Page2() {
643 return <div>page2</div>
644 }
645β
646 function App() {
647 const [show, setShow] = React.useState(true)
648 return (
649 <div>
650 {show ? <Page /> : <Page2 />}
651 <button onClick={() => setShow(false)}>hide</button>
652 </div>
653 )
654 }
655β
656 const rendered = renderWithClient(queryClient, <App />)
657β
658 await act(() => vi.advanceTimersByTimeAsync(200))
659β
660 rendered.getByText('loading')
661β
662 // unmount while still fetching
663 fireEvent.click(rendered.getByText('hide'))
664β
665 await act(() => vi.advanceTimersByTimeAsync(800))
666β
667 rendered.getByText('page2')
668β
669 // wait for query to be resolved
670 await act(() => vi.advanceTimersByTimeAsync(2000))
671β
672 expect(queryClient.getQueryData(key)).toBe('data')
673β
674 // wait for gc
675 await act(() => vi.advanceTimersByTimeAsync(1000))
676β
677 expect(queryClient.getQueryData(key)).toBe(undefined)
678 })
679 })
680β
681 it('should log an error when skipToken is passed as queryFn', () => {
682 const consoleErrorSpy = vi
683 .spyOn(console, 'error')
684 .mockImplementation(() => {})
685 const key = queryKey()
686β
687 function Page() {
688 useSuspenseQueries({
689 queries: [
690 {
691 queryKey: key,
692 // @ts-expect-error
693 queryFn: Math.random() >= 0 ? skipToken : () => Promise.resolve(5),
694 },
695 ],
696 })
697β
698 return null
699 }
700β
701 function App() {
702 return (
703 <React.Suspense fallback="Loading...">
704 <Page />
705 </React.Suspense>
706 )
707 }
708β
709 renderWithClient(queryClient, <App />)
710β
711 expect(consoleErrorSpy).toHaveBeenCalledWith(
712 'skipToken is not allowed for useSuspenseQueries',
713 )
714 consoleErrorSpy.mockRestore()
715 })
716β
717 it('should log an error when skipToken is used in development environment', () => {
718 const envCopy = process.env.NODE_ENV
719 process.env.NODE_ENV = 'development'
720β
721 const consoleErrorSpy = vi
722 .spyOn(console, 'error')
723 .mockImplementation(() => undefined)
724 const key = queryKey()
725β
726 function Page() {
727 useSuspenseQueries({
728 queries: [
729 {
730 queryKey: key,
731 queryFn: skipToken as any,
732 },
733 ],
734 })
735β
736 return null
737 }
738β
739 renderWithClient(
740 queryClient,
741 <React.Suspense fallback="Loading...">
742 <Page />
743 </React.Suspense>,
744 )
745β
746 expect(consoleErrorSpy).toHaveBeenCalledWith(
747 'skipToken is not allowed for useSuspenseQueries',
748 )
749β
750 consoleErrorSpy.mockRestore()
751 process.env.NODE_ENV = envCopy
752 })
753β
754 it('should not log an error when skipToken is used in production environment', () => {
755 const envCopy = process.env.NODE_ENV
756 process.env.NODE_ENV = 'production'
757β
758 const consoleErrorSpy = vi
759 .spyOn(console, 'error')
760 .mockImplementation(() => undefined)
761 const key = queryKey()
762β
763 function Page() {
764 useSuspenseQueries({
765 queries: [
766 {
767 queryKey: key,
768 queryFn: skipToken as any,
769 },
770 ],
771 })
772β
773 return null
774 }
775β
776 renderWithClient(
777 queryClient,
778 <React.Suspense fallback="Loading...">
779 <Page />
780 </React.Suspense>,
781 )
782β
783 expect(consoleErrorSpy).not.toHaveBeenCalled()
784β
785 consoleErrorSpy.mockRestore()
786 process.env.NODE_ENV = envCopy
787 })
788})