Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

usePrefetchQuery.test.tsx

324 lines9.0 KB

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​
15describe('usePrefetchQuery', () => {
16 let queryCache: QueryCache
17 let queryClient: QueryClient
18​
19 beforeEach(() => {
20 vi.useFakeTimers()
21 queryCache = new QueryCache()
22 queryClient = new QueryClient({ queryCache })
23 })
24​
25 afterEach(() => {
26 queryClient.clear()
27 vi.useRealTimers()
28 })
29​
30 it('should prefetch query if query state does not exist', async () => {
31 const queryOpts = {
32 queryKey: queryKey(),
33 queryFn: vi.fn(() => sleep(10).then(() => 'prefetchQuery')),
34 }
35​
36 const componentQueryOpts = {
37 ...queryOpts,
38 queryFn: () => sleep(10).then(() => 'useSuspenseQuery'),
39 }
40​
41 function Page() {
42 const state = useSuspenseQuery(componentQueryOpts)
43 return <div>data: {String(state.data)}</div>
44 }
45​
46 function App() {
47 usePrefetchQuery(queryOpts)
48​
49 return (
50 <React.Suspense fallback="Loading...">
51 <Page />
52 </React.Suspense>
53 )
54 }
55​
56 const rendered = renderWithClient(queryClient, <App />)
57​
58 expect(rendered.getByText('Loading...')).toBeInTheDocument()
59​
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.fetchQuery(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 consoleMock = vi.spyOn(console, 'error')
102 consoleMock.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 queryClient.prefetchQuery(queryOpts)
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 consoleMock.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 await act(() => vi.advanceTimersByTimeAsync(10))
175 expect(rendered.getByText('data: prefetchedQuery')).toBeInTheDocument()
176 expect(queryOpts.queryFn).toHaveBeenCalledTimes(1)
177 })
178​
179 it('should be able to recover from errors and try fetching again', async () => {
180 const consoleMock = vi.spyOn(console, 'error')
181 consoleMock.mockImplementation(() => undefined)
182 const queryFn = vi.fn(() =>
183 sleep(10).then(() => 'This is fine :dog: :fire:'),
184 )
185​
186 const queryOpts = {
187 queryKey: queryKey(),
188 queryFn,
189 }
190​
191 queryFn.mockImplementationOnce(() =>
192 sleep(10).then(() => {
193 throw new Error('Oops! Server error!')
194 }),
195 )
196​
197 function Page() {
198 const state = useSuspenseQuery(queryOpts)
199 return <div>data: {String(state.data)}</div>
200 }
201​
202 function App() {
203 const { reset } = useQueryErrorResetBoundary()
204 usePrefetchQuery(queryOpts)
205​
206 return (
207 <ErrorBoundary
208 onReset={reset}
209 fallbackRender={({ resetErrorBoundary }) => (
210 <div>
211 <div>Oops!</div>
212 <button onClick={resetErrorBoundary}>Try again</button>
213 </div>
214 )}
215 >
216 <React.Suspense fallback="Loading...">
217 <Page />
218 </React.Suspense>
219 </ErrorBoundary>
220 )
221 }
222​
223 queryClient.prefetchQuery(queryOpts)
224 await vi.advanceTimersByTimeAsync(10)
225 queryFn.mockClear()
226​
227 const rendered = renderWithClient(queryClient, <App />)
228​
229 expect(rendered.getByText('Oops!')).toBeInTheDocument()
230 fireEvent.click(rendered.getByText('Try again'))
231 await act(() => vi.advanceTimersByTimeAsync(10))
232 expect(
233 rendered.getByText('data: This is fine :dog: :fire:'),
234 ).toBeInTheDocument()
235 expect(queryOpts.queryFn).toHaveBeenCalledTimes(1)
236 consoleMock.mockRestore()
237 })
238​
239 it('should not create a suspense waterfall if prefetch is fired', async () => {
240 const firstQueryOpts = {
241 queryKey: queryKey(),
242 queryFn: vi.fn(() => sleep(10).then(() => 'Prefetch is nice!')),
243 }
244​
245 const secondQueryOpts = {
246 queryKey: queryKey(),
247 queryFn: vi.fn(() => sleep(10).then(() => 'Prefetch is really nice!!')),
248 }
249​
250 const thirdQueryOpts = {
251 queryKey: queryKey(),
252 queryFn: vi.fn(() =>
253 sleep(10).then(() => 'Prefetch does not create waterfalls!!'),
254 ),
255 }
256​
257 const Fallback = vi.fn().mockImplementation(() => <div>Loading...</div>)
258​
259 function FirstQuery({ children }: { children?: React.ReactNode }) {
260 const state = useSuspenseQuery(firstQueryOpts)
261 return (
262 <div>
263 <div>data: {String(state.data)}</div>
264 {children}
265 </div>
266 )
267 }
268​
269 function SecondQuery({ children }: { children?: React.ReactNode }) {
270 const state = useSuspenseQuery(secondQueryOpts)
271 return (
272 <div>
273 <div>data: {String(state.data)}</div>
274 {children}
275 </div>
276 )
277 }
278​
279 function ThirdQuery() {
280 const state = useSuspenseQuery(thirdQueryOpts)
281 return <div>data: {String(state.data)}</div>
282 }
283​
284 function App() {
285 usePrefetchQuery(firstQueryOpts)
286 usePrefetchQuery(secondQueryOpts)
287 usePrefetchQuery(thirdQueryOpts)
288​
289 return (
290 <React.Suspense fallback={<Fallback />}>
291 <FirstQuery>
292 <SecondQuery>
293 <ThirdQuery />
294 </SecondQuery>
295 </FirstQuery>
296 </React.Suspense>
297 )
298 }
299​
300 const rendered = renderWithClient(queryClient, <App />)
301 expect(
302 queryClient.getQueryState(firstQueryOpts.queryKey)?.fetchStatus,
303 ).toBe('fetching')
304 expect(
305 queryClient.getQueryState(secondQueryOpts.queryKey)?.fetchStatus,
306 ).toBe('fetching')
307 expect(
308 queryClient.getQueryState(thirdQueryOpts.queryKey)?.fetchStatus,
309 ).toBe('fetching')
310 expect(rendered.getByText('Loading...')).toBeInTheDocument()
311 await act(() => vi.advanceTimersByTimeAsync(10))
312 expect(rendered.getByText('data: Prefetch is nice!')).toBeInTheDocument()
313 expect(
314 rendered.getByText('data: Prefetch is really nice!!'),
315 ).toBeInTheDocument()
316 expect(
317 rendered.getByText('data: Prefetch does not create waterfalls!!'),
318 ).toBeInTheDocument()
319 expect(Fallback).toHaveBeenCalledTimes(1)
320 expect(firstQueryOpts.queryFn).toHaveBeenCalledTimes(1)
321 expect(secondQueryOpts.queryFn).toHaveBeenCalledTimes(1)
322 expect(thirdQueryOpts.queryFn).toHaveBeenCalledTimes(1)
323 })
324})