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