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

usePrefetchQuery.test.tsx

329 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 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​
63 await vi.advanceTimersByTimeAsync(10)
64 expect(rendered.getByText('data: prefetchQuery')).toBeInTheDocument()
65 expect(queryOpts.queryFn).toHaveBeenCalledTimes(1)
66 })
67​
68 it('should not prefetch query if query state exists', async () => {
69 const queryOpts = {
70 queryKey: queryKey(),
71 queryFn: vi.fn(() =>
72 sleep(10).then(() => 'The usePrefetchQuery hook is smart!'),
73 ),
74 }
75​
76 function Page() {
77 const state = useSuspenseQuery(queryOpts)
78 return <div>data: {String(state.data)}</div>
79 }
80​
81 function App() {
82 usePrefetchQuery(queryOpts)
83​
84 return (
85 <Suspense fallback="Loading...">
86 <Page />
87 </Suspense>
88 )
89 }
90​
91 void queryClient.query(queryOpts).catch(noop)
92 await vi.advanceTimersByTimeAsync(10)
93 queryOpts.queryFn.mockClear()
94 const rendered = renderWithClient(queryClient, <App />)
95​
96 expect(rendered.queryByText('fetching: true')).not.toBeInTheDocument()
97 expect(
98 rendered.getByText('data: The usePrefetchQuery hook is smart!'),
99 ).toBeInTheDocument()
100 expect(queryOpts.queryFn).not.toHaveBeenCalled()
101 })
102​
103 it('should let errors fall through and not refetch failed queries', async () => {
104 const consoleMock = vi.spyOn(console, 'error')
105 consoleMock.mockImplementation(() => undefined)
106 const queryFn = vi.fn(() => sleep(10).then(() => 'Not an error'))
107​
108 const queryOpts = {
109 queryKey: queryKey(),
110 queryFn,
111 }
112​
113 queryFn.mockImplementationOnce(() =>
114 sleep(10).then(() => {
115 throw new Error('Oops! Server error!')
116 }),
117 )
118​
119 function Page() {
120 const state = useSuspenseQuery(queryOpts)
121 return <div>data: {String(state.data)}</div>
122 }
123​
124 function App() {
125 usePrefetchQuery(queryOpts)
126​
127 return (
128 <ErrorBoundary fallbackRender={() => <div>Oops!</div>}>
129 <Suspense fallback="Loading...">
130 <Page />
131 </Suspense>
132 </ErrorBoundary>
133 )
134 }
135​
136 void queryClient.query(queryOpts).catch(noop)
137 await vi.advanceTimersByTimeAsync(10)
138 queryFn.mockClear()
139 const rendered = renderWithClient(queryClient, <App />)
140​
141 expect(rendered.getByText('Oops!')).toBeInTheDocument()
142 expect(rendered.queryByText('data: Not an error')).not.toBeInTheDocument()
143 expect(queryOpts.queryFn).not.toHaveBeenCalled()
144​
145 consoleMock.mockRestore()
146 })
147​
148 it('should not create an endless loop when using inside a suspense boundary', async () => {
149 const queryFn = vi.fn(() => sleep(10).then(() => 'prefetchedQuery'))
150​
151 const queryOpts = {
152 queryKey: queryKey(),
153 queryFn,
154 }
155​
156 function Prefetch({ children }: { children: VNode }) {
157 usePrefetchQuery(queryOpts)
158 return <>{children}</>
159 }
160​
161 function Page() {
162 const state = useSuspenseQuery(queryOpts)
163 return <div>data: {String(state.data)}</div>
164 }
165​
166 function App() {
167 return (
168 <Suspense fallback={<></>}>
169 <Prefetch>
170 <Page />
171 </Prefetch>
172 </Suspense>
173 )
174 }
175​
176 const rendered = renderWithClient(queryClient, <App />)
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 consoleMock = vi.spyOn(console, 'error')
184 consoleMock.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 fireEvent.click(rendered.getByText('Try again'))
234 await vi.advanceTimersByTimeAsync(10)
235 expect(
236 rendered.getByText('data: This is fine :dog: :fire:'),
237 ).toBeInTheDocument()
238 expect(queryOpts.queryFn).toHaveBeenCalledTimes(1)
239 consoleMock.mockRestore()
240 })
241​
242 it('should not create a suspense waterfall if prefetch is fired', async () => {
243 const firstQueryOpts = {
244 queryKey: queryKey(),
245 queryFn: vi.fn(() => sleep(10).then(() => 'Prefetch is nice!')),
246 }
247​
248 const secondQueryOpts = {
249 queryKey: queryKey(),
250 queryFn: vi.fn(() => sleep(10).then(() => 'Prefetch is really nice!!')),
251 }
252​
253 const thirdQueryOpts = {
254 queryKey: queryKey(),
255 queryFn: vi.fn(() =>
256 sleep(10).then(() => 'Prefetch does not create waterfalls!!'),
257 ),
258 }
259​
260 const Fallback = vi.fn().mockImplementation(() => <div>Loading...</div>)
261​
262 function FirstQuery({ children }: { children?: VNode }) {
263 const state = useSuspenseQuery(firstQueryOpts)
264 return (
265 <div>
266 <div>data: {String(state.data)}</div>
267 {children}
268 </div>
269 )
270 }
271​
272 function SecondQuery({ children }: { children?: VNode }) {
273 const state = useSuspenseQuery(secondQueryOpts)
274 return (
275 <div>
276 <div>data: {String(state.data)}</div>
277 {children}
278 </div>
279 )
280 }
281​
282 function ThirdQuery() {
283 const state = useSuspenseQuery(thirdQueryOpts)
284 return <div>data: {String(state.data)}</div>
285 }
286​
287 function App() {
288 usePrefetchQuery(firstQueryOpts)
289 usePrefetchQuery(secondQueryOpts)
290 usePrefetchQuery(thirdQueryOpts)
291​
292 return (
293 <Suspense fallback={<Fallback />}>
294 <FirstQuery>
295 <SecondQuery>
296 <ThirdQuery />
297 </SecondQuery>
298 </FirstQuery>
299 </Suspense>
300 )
301 }
302​
303 const rendered = renderWithClient(queryClient, <App />)
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(async () => {
315 await vi.advanceTimersByTimeAsync(10)
316 })
317 expect(rendered.getByText('data: Prefetch is nice!')).toBeInTheDocument()
318 expect(
319 rendered.getByText('data: Prefetch is really nice!!'),
320 ).toBeInTheDocument()
321 expect(
322 rendered.getByText('data: Prefetch does not create waterfalls!!'),
323 ).toBeInTheDocument()
324 expect(Fallback).toHaveBeenCalledTimes(1)
325 expect(firstQueryOpts.queryFn).toHaveBeenCalledTimes(1)
326 expect(secondQueryOpts.queryFn).toHaveBeenCalledTimes(1)
327 expect(thirdQueryOpts.queryFn).toHaveBeenCalledTimes(1)
328 })
329})