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

usePrefetchQuery.test.tsx

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