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