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