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

usePrefetchQuery.test.tsx

328 lines8.9 KB

1import { queryKey, sleep } from '@tanstack/query-test-utils'
2import { act, fireEvent } from '@testing-library/preact'
3import type { VNode } from 'preact'
4import { Suspense } from 'preact/compat'
5import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
6​
7import {
8 QueryCache,
9 QueryClient,
10 usePrefetchQuery,
11 useQueryErrorResetBoundary,
12 useSuspenseQuery,
13} from '..'
14import { ErrorBoundary } from './ErrorBoundary'
15import { renderWithClient } from './utils'
16​
17describe('usePrefetchQuery', () => {
18 let queryCache: QueryCache
19 let queryClient: QueryClient
20​
21 beforeEach(() => {
22 vi.useFakeTimers()
23 queryCache = new QueryCache()
24 queryClient = new QueryClient({ queryCache })
25 })
26​
27 afterEach(() => {
28 queryClient.clear()
29 vi.useRealTimers()
30 })
31​
32 it('should prefetch query if query state does not exist', async () => {
33 const queryOpts = {
34 queryKey: queryKey(),
35 queryFn: vi.fn(() => sleep(10).then(() => 'prefetchQuery')),
36 }
37​
38 const componentQueryOpts = {
39 ...queryOpts,
40 queryFn: () => sleep(10).then(() => 'useSuspenseQuery'),
41 }
42​
43 function Page() {
44 const state = useSuspenseQuery(componentQueryOpts)
45 return <div>data: {String(state.data)}</div>
46 }
47​
48 function App() {
49 usePrefetchQuery(queryOpts)
50​
51 return (
52 <Suspense fallback="Loading...">
53 <Page />
54 </Suspense>
55 )
56 }
57​
58 const rendered = renderWithClient(queryClient, <App />)
59​
60 expect(rendered.getByText('Loading...')).toBeInTheDocument()
61​
62 await 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: queryKey(),
70 queryFn: vi.fn(() =>
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 <Suspense fallback="Loading...">
85 <Page />
86 </Suspense>
87 )
88 }
89​
90 queryClient.fetchQuery(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 consoleMock = vi.spyOn(console, 'error')
104 consoleMock.mockImplementation(() => undefined)
105 const queryFn = vi.fn(() => sleep(10).then(() => 'Not an error'))
106​
107 const queryOpts = {
108 queryKey: queryKey(),
109 queryFn,
110 }
111​
112 queryFn.mockImplementationOnce(() =>
113 sleep(10).then(() => {
114 throw new Error('Oops! Server error!')
115 }),
116 )
117​
118 function Page() {
119 const state = useSuspenseQuery(queryOpts)
120 return <div>data: {String(state.data)}</div>
121 }
122​
123 function App() {
124 usePrefetchQuery(queryOpts)
125​
126 return (
127 <ErrorBoundary fallbackRender={() => <div>Oops!</div>}>
128 <Suspense fallback="Loading...">
129 <Page />
130 </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 = vi.fn(() => sleep(10).then(() => 'prefetchedQuery'))
149​
150 const queryOpts = {
151 queryKey: queryKey(),
152 queryFn,
153 }
154​
155 function Prefetch({ children }: { children: VNode }) {
156 usePrefetchQuery(queryOpts)
157 return <>{children}</>
158 }
159​
160 function Page() {
161 const state = useSuspenseQuery(queryOpts)
162 return <div>data: {String(state.data)}</div>
163 }
164​
165 function App() {
166 return (
167 <Suspense fallback={<></>}>
168 <Prefetch>
169 <Page />
170 </Prefetch>
171 </Suspense>
172 )
173 }
174​
175 const rendered = renderWithClient(queryClient, <App />)
176 await vi.advanceTimersByTimeAsync(10)
177 expect(rendered.getByText('data: prefetchedQuery')).toBeInTheDocument()
178 expect(queryOpts.queryFn).toHaveBeenCalledTimes(1)
179 })
180​
181 it('should be able to recover from errors and try fetching again', async () => {
182 const consoleMock = vi.spyOn(console, 'error')
183 consoleMock.mockImplementation(() => undefined)
184 const queryFn = vi.fn(() =>
185 sleep(10).then(() => 'This is fine :dog: :fire:'),
186 )
187​
188 const queryOpts = {
189 queryKey: queryKey(),
190 queryFn,
191 }
192​
193 queryFn.mockImplementationOnce(() =>
194 sleep(10).then(() => {
195 throw new Error('Oops! Server error!')
196 }),
197 )
198​
199 function Page() {
200 const state = useSuspenseQuery(queryOpts)
201 return <div>data: {String(state.data)}</div>
202 }
203​
204 function App() {
205 const { reset } = useQueryErrorResetBoundary()
206 usePrefetchQuery(queryOpts)
207​
208 return (
209 <ErrorBoundary
210 onReset={reset}
211 fallbackRender={({ resetErrorBoundary }) => (
212 <div>
213 <div>Oops!</div>
214 <button onClick={resetErrorBoundary}>Try again</button>
215 </div>
216 )}
217 >
218 <Suspense fallback="Loading...">
219 <Page />
220 </Suspense>
221 </ErrorBoundary>
222 )
223 }
224​
225 queryClient.prefetchQuery(queryOpts)
226 await vi.advanceTimersByTimeAsync(10)
227 queryFn.mockClear()
228​
229 const rendered = renderWithClient(queryClient, <App />)
230​
231 expect(rendered.getByText('Oops!')).toBeInTheDocument()
232 fireEvent.click(rendered.getByText('Try again'))
233 await vi.advanceTimersByTimeAsync(10)
234 expect(
235 rendered.getByText('data: This is fine :dog: :fire:'),
236 ).toBeInTheDocument()
237 expect(queryOpts.queryFn).toHaveBeenCalledTimes(1)
238 consoleMock.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?: VNode }) {
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?: VNode }) {
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 <Suspense fallback={<Fallback />}>
293 <FirstQuery>
294 <SecondQuery>
295 <ThirdQuery />
296 </SecondQuery>
297 </FirstQuery>
298 </Suspense>
299 )
300 }
301​
302 const rendered = renderWithClient(queryClient, <App />)
303 expect(
304 queryClient.getQueryState(firstQueryOpts.queryKey)?.fetchStatus,
305 ).toBe('fetching')
306 expect(
307 queryClient.getQueryState(secondQueryOpts.queryKey)?.fetchStatus,
308 ).toBe('fetching')
309 expect(
310 queryClient.getQueryState(thirdQueryOpts.queryKey)?.fetchStatus,
311 ).toBe('fetching')
312 expect(rendered.getByText('Loading...')).toBeInTheDocument()
313 await act(async () => {
314 await vi.advanceTimersByTimeAsync(10)
315 })
316 expect(rendered.getByText('data: Prefetch is nice!')).toBeInTheDocument()
317 expect(
318 rendered.getByText('data: Prefetch is really nice!!'),
319 ).toBeInTheDocument()
320 expect(
321 rendered.getByText('data: Prefetch does not create waterfalls!!'),
322 ).toBeInTheDocument()
323 expect(Fallback).toHaveBeenCalledTimes(1)
324 expect(firstQueryOpts.queryFn).toHaveBeenCalledTimes(1)
325 expect(secondQueryOpts.queryFn).toHaveBeenCalledTimes(1)
326 expect(thirdQueryOpts.queryFn).toHaveBeenCalledTimes(1)
327 })
328})