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

usePrefetchQuery.test.tsx

341 lines9.5 KB

1import { createKey, sleep } from '@tanstack/query-test-utils'
2import { act, fireEvent } from '@testing-library/preact'
3import { Suspense } from 'preact/compat'
4import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
5import {
6 QueryCache,
7 QueryClient,
8 noop,
9 usePrefetchQuery,
10 useQueryErrorResetBoundary,
11 useSuspenseQuery,
12} from '..'
13import { ErrorBoundary } from './ErrorBoundary'
14import { renderWithClient } from './utils'
15import type { JSX, VNode } from 'preact'
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: createKey(),
35 queryFn: vi.fn<() => Promise<string>>(() =>
36 sleep(10).then(() => 'prefetchQuery'),
37 ),
38 }
39​
40 const componentQueryOpts = {
41 ...queryOpts,
42 queryFn: () => sleep(10).then(() => 'useSuspenseQuery'),
43 }
44​
45 function Page() {
46 const state = useSuspenseQuery(componentQueryOpts)
47 return <div>data: {String(state.data)}</div>
48 }
49​
50 function App() {
51 usePrefetchQuery(queryOpts)
52​
53 return (
54 <Suspense fallback="Loading...">
55 <Page />
56 </Suspense>
57 )
58 }
59​
60 const rendered = renderWithClient(queryClient, <App />)
61​
62 expect(rendered.getByText('Loading...')).toBeInTheDocument()
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: createKey(),
71 queryFn: vi.fn<() => Promise<string>>(() =>
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 consoleErrorMock = vi.spyOn(console, 'error')
105 consoleErrorMock.mockReturnValue(undefined)
106 const queryFn = vi.fn<() => Promise<string>>(() =>
107 sleep(10).then(() => 'Not an error'),
108 )
109​
110 const queryOpts = {
111 queryKey: createKey(),
112 queryFn,
113 }
114​
115 // oxlint-disable-next-line vitest/prefer-mock-return-shorthand -- the promise must be created when the mock is called, not when it is set up
116 queryFn.mockImplementationOnce(() =>
117 sleep(10).then(() => {
118 throw new Error('Oops! Server error!')
119 }),
120 )
121​
122 function Page() {
123 const state = useSuspenseQuery(queryOpts)
124 return <div>data: {String(state.data)}</div>
125 }
126​
127 function App() {
128 usePrefetchQuery(queryOpts)
129​
130 return (
131 <ErrorBoundary fallbackRender={() => <div>Oops!</div>}>
132 <Suspense fallback="Loading...">
133 <Page />
134 </Suspense>
135 </ErrorBoundary>
136 )
137 }
138​
139 void queryClient.query(queryOpts).catch(noop)
140 await vi.advanceTimersByTimeAsync(10)
141 queryFn.mockClear()
142 const rendered = renderWithClient(queryClient, <App />)
143​
144 expect(rendered.getByText('Oops!')).toBeInTheDocument()
145 expect(rendered.queryByText('data: Not an error')).not.toBeInTheDocument()
146 expect(queryOpts.queryFn).not.toHaveBeenCalled()
147 })
148​
149 it('should not create an endless loop when using inside a suspense boundary', async () => {
150 const queryFn = vi.fn<() => Promise<string>>(() =>
151 sleep(10).then(() => 'prefetchedQuery'),
152 )
153​
154 const queryOpts = {
155 queryKey: createKey(),
156 queryFn,
157 }
158​
159 function Prefetch({ children }: { children: VNode }) {
160 usePrefetchQuery(queryOpts)
161 return <>{children}</>
162 }
163​
164 function Page() {
165 const state = useSuspenseQuery(queryOpts)
166 return <div>data: {String(state.data)}</div>
167 }
168​
169 function App() {
170 return (
171 <Suspense fallback={<></>}>
172 <Prefetch>
173 <Page />
174 </Prefetch>
175 </Suspense>
176 )
177 }
178​
179 const rendered = renderWithClient(queryClient, <App />)
180​
181 await vi.advanceTimersByTimeAsync(10)
182 expect(rendered.getByText('data: prefetchedQuery')).toBeInTheDocument()
183 expect(queryOpts.queryFn).toHaveBeenCalledTimes(1)
184 })
185​
186 it('should be able to recover from errors and try fetching again', async () => {
187 const consoleErrorMock = vi.spyOn(console, 'error')
188 consoleErrorMock.mockReturnValue(undefined)
189 const queryFn = vi.fn<() => Promise<string>>(() =>
190 sleep(10).then(() => 'This is fine :dog: :fire:'),
191 )
192​
193 const queryOpts = {
194 queryKey: createKey(),
195 queryFn,
196 }
197​
198 // oxlint-disable-next-line vitest/prefer-mock-return-shorthand -- the promise must be created when the mock is called, not when it is set up
199 queryFn.mockImplementationOnce(() =>
200 sleep(10).then(() => {
201 throw new Error('Oops! Server error!')
202 }),
203 )
204​
205 function Page() {
206 const state = useSuspenseQuery(queryOpts)
207 return <div>data: {String(state.data)}</div>
208 }
209​
210 function App() {
211 const { reset } = useQueryErrorResetBoundary()
212 usePrefetchQuery(queryOpts)
213​
214 return (
215 <ErrorBoundary
216 onReset={reset}
217 fallbackRender={({ resetErrorBoundary }) => (
218 <div>
219 <div>Oops!</div>
220 <button onClick={resetErrorBoundary}>Try again</button>
221 </div>
222 )}
223 >
224 <Suspense fallback="Loading...">
225 <Page />
226 </Suspense>
227 </ErrorBoundary>
228 )
229 }
230​
231 void queryClient.query(queryOpts).catch(noop)
232 await vi.advanceTimersByTimeAsync(10)
233 queryFn.mockClear()
234​
235 const rendered = renderWithClient(queryClient, <App />)
236​
237 expect(rendered.getByText('Oops!')).toBeInTheDocument()
238​
239 fireEvent.click(rendered.getByText('Try again'))
240 await vi.advanceTimersByTimeAsync(10)
241 expect(
242 rendered.getByText('data: This is fine :dog: :fire:'),
243 ).toBeInTheDocument()
244 expect(queryOpts.queryFn).toHaveBeenCalledTimes(1)
245 })
246​
247 it('should not create a suspense waterfall if prefetch is fired', async () => {
248 const firstQueryOpts = {
249 queryKey: createKey(),
250 queryFn: vi.fn<() => Promise<string>>(() =>
251 sleep(10).then(() => 'Prefetch is nice!'),
252 ),
253 }
254​
255 const secondQueryOpts = {
256 queryKey: createKey(),
257 queryFn: vi.fn<() => Promise<string>>(() =>
258 sleep(10).then(() => 'Prefetch is really nice!!'),
259 ),
260 }
261​
262 const thirdQueryOpts = {
263 queryKey: createKey(),
264 queryFn: vi.fn<() => Promise<string>>(() =>
265 sleep(10).then(() => 'Prefetch does not create waterfalls!!'),
266 ),
267 }
268​
269 const Fallback = vi
270 .fn<() => JSX.Element>()
271 .mockReturnValue(<div>Loading...</div>)
272​
273 function FirstQuery({ children }: { children?: VNode }) {
274 const state = useSuspenseQuery(firstQueryOpts)
275 return (
276 <div>
277 <div>data: {String(state.data)}</div>
278 {children}
279 </div>
280 )
281 }
282​
283 function SecondQuery({ children }: { children?: VNode }) {
284 const state = useSuspenseQuery(secondQueryOpts)
285 return (
286 <div>
287 <div>data: {String(state.data)}</div>
288 {children}
289 </div>
290 )
291 }
292​
293 function ThirdQuery() {
294 const state = useSuspenseQuery(thirdQueryOpts)
295 return <div>data: {String(state.data)}</div>
296 }
297​
298 function App() {
299 usePrefetchQuery(firstQueryOpts)
300 usePrefetchQuery(secondQueryOpts)
301 usePrefetchQuery(thirdQueryOpts)
302​
303 return (
304 <Suspense fallback={<Fallback />}>
305 <FirstQuery>
306 <SecondQuery>
307 <ThirdQuery />
308 </SecondQuery>
309 </FirstQuery>
310 </Suspense>
311 )
312 }
313​
314 const rendered = renderWithClient(queryClient, <App />)
315​
316 expect(
317 queryClient.getQueryState(firstQueryOpts.queryKey)?.fetchStatus,
318 ).toBe('fetching')
319 expect(
320 queryClient.getQueryState(secondQueryOpts.queryKey)?.fetchStatus,
321 ).toBe('fetching')
322 expect(
323 queryClient.getQueryState(thirdQueryOpts.queryKey)?.fetchStatus,
324 ).toBe('fetching')
325 expect(rendered.getByText('Loading...')).toBeInTheDocument()
326 await act(async () => {
327 await vi.advanceTimersByTimeAsync(10)
328 })
329 expect(rendered.getByText('data: Prefetch is nice!')).toBeInTheDocument()
330 expect(
331 rendered.getByText('data: Prefetch is really nice!!'),
332 ).toBeInTheDocument()
333 expect(
334 rendered.getByText('data: Prefetch does not create waterfalls!!'),
335 ).toBeInTheDocument()
336 expect(Fallback).toHaveBeenCalledTimes(1)
337 expect(firstQueryOpts.queryFn).toHaveBeenCalledTimes(1)
338 expect(secondQueryOpts.queryFn).toHaveBeenCalledTimes(1)
339 expect(thirdQueryOpts.queryFn).toHaveBeenCalledTimes(1)
340 })
341})