Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

useSuspenseQueries.test.tsx

788 lines18.7 KB

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})