Open History to see the last commit
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})