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