Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2import * as React from 'react'
3import { act, fireEvent } from '@testing-library/react'
4import { ErrorBoundary } from 'react-error-boundary'
5import { queryKey, sleep } from '@tanstack/query-test-utils'
6import {
7 QueryCache,
8 QueryClient,
9 usePrefetchQuery,
10 useQueryErrorResetBoundary,
11 useSuspenseQuery,
12} from '..'
13import { renderWithClient } from './utils'
14β
15import type { UseSuspenseQueryOptions } from '..'
16β
17const generateQueryFn = (data: string) =>
18 vi
19 .fn<(...args: Array<any>) => Promise<string>>()
20 .mockImplementation(() => sleep(10).then(() => data))
21β
22describe('usePrefetchQuery', () => {
23 let queryCache: QueryCache
24 let queryClient: QueryClient
25β
26 beforeEach(() => {
27 vi.useFakeTimers()
28 queryCache = new QueryCache()
29 queryClient = new QueryClient({ queryCache })
30 })
31β
32 afterEach(() => {
33 vi.useRealTimers()
34 queryClient.clear()
35 })
36β
37 function Suspended<TData = unknown>(props: {
38 queryOpts: UseSuspenseQueryOptions<TData, Error, TData, Array<string>>
39 children?: React.ReactNode
40 }) {
41 const state = useSuspenseQuery(props.queryOpts)
42β
43 return (
44 <div>
45 <div>data: {String(state.data)}</div>
46 {props.children}
47 </div>
48 )
49 }
50β
51 it('should prefetch query if query state does not exist', async () => {
52 const queryOpts = {
53 queryKey: queryKey(),
54 queryFn: generateQueryFn('prefetchQuery'),
55 }
56β
57 const componentQueryOpts = {
58 ...queryOpts,
59 queryFn: generateQueryFn('useSuspenseQuery'),
60 }
61β
62 function App() {
63 usePrefetchQuery(queryOpts)
64β
65 return (
66 <React.Suspense fallback="Loading...">
67 <Suspended queryOpts={componentQueryOpts} />
68 </React.Suspense>
69 )
70 }
71β
72 const rendered = renderWithClient(queryClient, <App />)
73β
74 await act(() => vi.advanceTimersByTimeAsync(10))
75 expect(rendered.getByText('data: prefetchQuery')).toBeInTheDocument()
76 expect(queryOpts.queryFn).toHaveBeenCalledTimes(1)
77 })
78β
79 it('should not prefetch query if query state exists', async () => {
80 const queryOpts = {
81 queryKey: queryKey(),
82 queryFn: generateQueryFn('The usePrefetchQuery hook is smart!'),
83 }
84β
85 function App() {
86 usePrefetchQuery(queryOpts)
87β
88 return (
89 <React.Suspense fallback="Loading...">
90 <Suspended queryOpts={queryOpts} />
91 </React.Suspense>
92 )
93 }
94β
95 queryClient.fetchQuery(queryOpts)
96 await vi.advanceTimersByTimeAsync(10)
97 queryOpts.queryFn.mockClear()
98 const rendered = renderWithClient(queryClient, <App />)
99β
100 expect(rendered.queryByText('fetching: true')).not.toBeInTheDocument()
101 expect(
102 rendered.getByText('data: The usePrefetchQuery hook is smart!'),
103 ).toBeInTheDocument()
104 expect(queryOpts.queryFn).not.toHaveBeenCalled()
105 })
106β
107 it('should let errors fall through and not refetch failed queries', async () => {
108 const consoleMock = vi.spyOn(console, 'error')
109 consoleMock.mockImplementation(() => undefined)
110 const queryFn = generateQueryFn('Not an error')
111β
112 const queryOpts = {
113 queryKey: queryKey(),
114 queryFn,
115 }
116β
117 queryFn.mockImplementationOnce(async () => {
118 await sleep(10)
119β
120 throw new Error('Oops! Server error!')
121 })
122β
123 function App() {
124 usePrefetchQuery(queryOpts)
125β
126 return (
127 <ErrorBoundary fallbackRender={() => <div>Oops!</div>}>
128 <React.Suspense fallback="Loading...">
129 <Suspended queryOpts={queryOpts} />
130 </React.Suspense>
131 </ErrorBoundary>
132 )
133 }
134β
135 queryClient.prefetchQuery(queryOpts)
136 await vi.advanceTimersByTimeAsync(10)
137 queryFn.mockClear()
138 const rendered = renderWithClient(queryClient, <App />)
139β
140 expect(rendered.getByText('Oops!')).toBeInTheDocument()
141 expect(rendered.queryByText('data: Not an error')).not.toBeInTheDocument()
142 expect(queryOpts.queryFn).not.toHaveBeenCalled()
143β
144 consoleMock.mockRestore()
145 })
146β
147 it('should not create an endless loop when using inside a suspense boundary', async () => {
148 const queryFn = generateQueryFn('prefetchedQuery')
149β
150 const queryOpts = {
151 queryKey: queryKey(),
152 queryFn,
153 }
154β
155 function Prefetch({ children }: { children: React.ReactNode }) {
156 usePrefetchQuery(queryOpts)
157 return <>{children}</>
158 }
159β
160 function App() {
161 return (
162 <React.Suspense>
163 <Prefetch>
164 <Suspended queryOpts={queryOpts} />
165 </Prefetch>
166 </React.Suspense>
167 )
168 }
169β
170 const rendered = renderWithClient(queryClient, <App />)
171 await act(() => vi.advanceTimersByTimeAsync(10))
172 expect(rendered.getByText('data: prefetchedQuery')).toBeInTheDocument()
173 expect(queryOpts.queryFn).toHaveBeenCalledTimes(1)
174 })
175β
176 it('should be able to recover from errors and try fetching again', async () => {
177 const consoleMock = vi.spyOn(console, 'error')
178 consoleMock.mockImplementation(() => undefined)
179 const queryFn = generateQueryFn('This is fine :dog: :fire:')
180β
181 const queryOpts = {
182 queryKey: queryKey(),
183 queryFn,
184 }
185β
186 queryFn.mockImplementationOnce(async () => {
187 await sleep(10)
188β
189 throw new Error('Oops! Server error!')
190 })
191β
192 function App() {
193 const { reset } = useQueryErrorResetBoundary()
194 usePrefetchQuery(queryOpts)
195β
196 return (
197 <ErrorBoundary
198 onReset={reset}
199 fallbackRender={({ resetErrorBoundary }) => (
200 <div>
201 <div>Oops!</div>
202 <button onClick={resetErrorBoundary}>Try again</button>
203 </div>
204 )}
205 >
206 <React.Suspense fallback="Loading...">
207 <Suspended queryOpts={queryOpts} />
208 </React.Suspense>
209 </ErrorBoundary>
210 )
211 }
212β
213 queryClient.prefetchQuery(queryOpts)
214 await vi.advanceTimersByTimeAsync(10)
215 queryFn.mockClear()
216β
217 const rendered = renderWithClient(queryClient, <App />)
218β
219 expect(rendered.getByText('Oops!')).toBeInTheDocument()
220 fireEvent.click(rendered.getByText('Try again'))
221 await act(() => vi.advanceTimersByTimeAsync(10))
222 expect(
223 rendered.getByText('data: This is fine :dog: :fire:'),
224 ).toBeInTheDocument()
225 expect(queryOpts.queryFn).toHaveBeenCalledTimes(1)
226 consoleMock.mockRestore()
227 })
228β
229 it('should not create a suspense waterfall if prefetch is fired', async () => {
230 const firstQueryOpts = {
231 queryKey: queryKey(),
232 queryFn: generateQueryFn('Prefetch is nice!'),
233 }
234β
235 const secondQueryOpts = {
236 queryKey: queryKey(),
237 queryFn: generateQueryFn('Prefetch is really nice!!'),
238 }
239β
240 const thirdQueryOpts = {
241 queryKey: queryKey(),
242 queryFn: generateQueryFn('Prefetch does not create waterfalls!!'),
243 }
244β
245 const Fallback = vi.fn().mockImplementation(() => <div>Loading...</div>)
246β
247 function App() {
248 usePrefetchQuery(firstQueryOpts)
249 usePrefetchQuery(secondQueryOpts)
250 usePrefetchQuery(thirdQueryOpts)
251β
252 return (
253 <React.Suspense fallback={<Fallback />}>
254 <Suspended queryOpts={firstQueryOpts}>
255 <Suspended queryOpts={secondQueryOpts}>
256 <Suspended queryOpts={thirdQueryOpts} />
257 </Suspended>
258 </Suspended>
259 </React.Suspense>
260 )
261 }
262β
263 const rendered = renderWithClient(queryClient, <App />)
264 expect(
265 queryClient.getQueryState(firstQueryOpts.queryKey)?.fetchStatus,
266 ).toBe('fetching')
267 expect(
268 queryClient.getQueryState(secondQueryOpts.queryKey)?.fetchStatus,
269 ).toBe('fetching')
270 expect(
271 queryClient.getQueryState(thirdQueryOpts.queryKey)?.fetchStatus,
272 ).toBe('fetching')
273 expect(rendered.getByText('Loading...')).toBeInTheDocument()
274 await act(() => vi.advanceTimersByTimeAsync(10))
275 expect(rendered.getByText('data: Prefetch is nice!')).toBeInTheDocument()
276 expect(
277 rendered.getByText('data: Prefetch is really nice!!'),
278 ).toBeInTheDocument()
279 expect(
280 rendered.getByText('data: Prefetch does not create waterfalls!!'),
281 ).toBeInTheDocument()
282 expect(Fallback).toHaveBeenCalledTimes(1)
283 expect(firstQueryOpts.queryFn).toHaveBeenCalledTimes(1)
284 expect(secondQueryOpts.queryFn).toHaveBeenCalledTimes(1)
285 expect(thirdQueryOpts.queryFn).toHaveBeenCalledTimes(1)
286 })
287})