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