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 type { UseSuspenseQueryOptions } from '..'
15import { ErrorBoundary } from './ErrorBoundary'
16import { renderWithClient } from './utils'
17β
18const generateQueryFn = (data: string) =>
19 vi
20 .fn<(...args: Array<any>) => Promise<string>>()
21 .mockImplementation(async () => {
22 await sleep(10)
23β
24 return data
25 })
26β
27describe('usePrefetchQuery', () => {
28 const queryCache = new QueryCache()
29 const queryClient = new QueryClient({ queryCache })
30β
31 beforeEach(() => {
32 vi.useFakeTimers()
33 })
34β
35 afterEach(() => {
36 vi.useRealTimers()
37 })
38β
39 function Suspended<TData = unknown>(props: {
40 queryOpts: UseSuspenseQueryOptions<TData, Error, TData, Array<string>>
41 children?: VNode
42 }) {
43 const state = useSuspenseQuery(props.queryOpts)
44β
45 return (
46 <div>
47 <div>data: {String(state.data)}</div>
48 {props.children}
49 </div>
50 )
51 }
52β
53 it('should prefetch query if query state does not exist', async () => {
54 const queryOpts = {
55 queryKey: queryKey(),
56 queryFn: generateQueryFn('prefetchQuery'),
57 }
58β
59 const componentQueryOpts = {
60 ...queryOpts,
61 queryFn: generateQueryFn('useSuspenseQuery'),
62 }
63β
64 function App() {
65 usePrefetchQuery(queryOpts)
66β
67 return (
68 <Suspense fallback="Loading...">
69 <Suspended queryOpts={componentQueryOpts} />
70 </Suspense>
71 )
72 }
73β
74 const rendered = renderWithClient(queryClient, <App />)
75β
76 await vi.advanceTimersByTimeAsync(10)
77 expect(rendered.getByText('data: prefetchQuery')).toBeInTheDocument()
78 expect(queryOpts.queryFn).toHaveBeenCalledTimes(1)
79 })
80β
81 it('should not prefetch query if query state exists', async () => {
82 const queryOpts = {
83 queryKey: queryKey(),
84 queryFn: generateQueryFn('The usePrefetchQuery hook is smart!'),
85 }
86β
87 function App() {
88 usePrefetchQuery(queryOpts)
89β
90 return (
91 <Suspense fallback="Loading...">
92 <Suspended queryOpts={queryOpts} />
93 </Suspense>
94 )
95 }
96β
97 queryClient.fetchQuery(queryOpts)
98 await vi.advanceTimersByTimeAsync(10)
99 queryOpts.queryFn.mockClear()
100 const rendered = renderWithClient(queryClient, <App />)
101β
102 expect(rendered.queryByText('fetching: true')).not.toBeInTheDocument()
103 expect(
104 rendered.getByText('data: The usePrefetchQuery hook is smart!'),
105 ).toBeInTheDocument()
106 expect(queryOpts.queryFn).not.toHaveBeenCalled()
107 })
108β
109 it('should let errors fall through and not refetch failed queries', async () => {
110 const consoleMock = vi.spyOn(console, 'error')
111 consoleMock.mockImplementation(() => undefined)
112 const queryFn = generateQueryFn('Not an error')
113β
114 const queryOpts = {
115 queryKey: queryKey(),
116 queryFn,
117 }
118β
119 queryFn.mockImplementationOnce(async () => {
120 await sleep(10)
121β
122 throw new Error('Oops! Server error!')
123 })
124β
125 function App() {
126 usePrefetchQuery(queryOpts)
127β
128 return (
129 <ErrorBoundary fallbackRender={() => <div>Oops!</div>}>
130 <Suspense fallback="Loading...">
131 <Suspended queryOpts={queryOpts} />
132 </Suspense>
133 </ErrorBoundary>
134 )
135 }
136β
137 queryClient.prefetchQuery(queryOpts)
138 await vi.advanceTimersByTimeAsync(10)
139 queryFn.mockClear()
140 const rendered = renderWithClient(queryClient, <App />)
141β
142 expect(rendered.getByText('Oops!')).toBeInTheDocument()
143 expect(rendered.queryByText('data: Not an error')).not.toBeInTheDocument()
144 expect(queryOpts.queryFn).not.toHaveBeenCalled()
145β
146 consoleMock.mockRestore()
147 })
148β
149 it('should not create an endless loop when using inside a suspense boundary', async () => {
150 const queryFn = generateQueryFn('prefetchedQuery')
151β
152 const queryOpts = {
153 queryKey: queryKey(),
154 queryFn,
155 }
156β
157 function Prefetch({ children }: { children: VNode }) {
158 usePrefetchQuery(queryOpts)
159 return <>{children}</>
160 }
161β
162 function App() {
163 return (
164 <Suspense fallback={<></>}>
165 <Prefetch>
166 <Suspended queryOpts={queryOpts} />
167 </Prefetch>
168 </Suspense>
169 )
170 }
171β
172 const rendered = renderWithClient(queryClient, <App />)
173 await vi.advanceTimersByTimeAsync(10)
174 expect(rendered.getByText('data: prefetchedQuery')).toBeInTheDocument()
175 expect(queryOpts.queryFn).toHaveBeenCalledTimes(1)
176 })
177β
178 it('should be able to recover from errors and try fetching again', async () => {
179 const consoleMock = vi.spyOn(console, 'error')
180 consoleMock.mockImplementation(() => undefined)
181 const queryFn = generateQueryFn('This is fine :dog: :fire:')
182β
183 const queryOpts = {
184 queryKey: queryKey(),
185 queryFn,
186 }
187β
188 queryFn.mockImplementationOnce(async () => {
189 await sleep(10)
190β
191 throw new Error('Oops! Server error!')
192 })
193β
194 function App() {
195 const { reset } = useQueryErrorResetBoundary()
196 usePrefetchQuery(queryOpts)
197β
198 return (
199 <ErrorBoundary
200 onReset={reset}
201 fallbackRender={({ resetErrorBoundary }) => (
202 <div>
203 <div>Oops!</div>
204 <button onClick={resetErrorBoundary}>Try again</button>
205 </div>
206 )}
207 >
208 <Suspense fallback="Loading...">
209 <Suspended queryOpts={queryOpts} />
210 </Suspense>
211 </ErrorBoundary>
212 )
213 }
214β
215 queryClient.prefetchQuery(queryOpts)
216 await vi.advanceTimersByTimeAsync(10)
217 queryFn.mockClear()
218β
219 const rendered = renderWithClient(queryClient, <App />)
220β
221 expect(rendered.getByText('Oops!')).toBeInTheDocument()
222 fireEvent.click(rendered.getByText('Try again'))
223 await vi.advanceTimersByTimeAsync(10)
224 expect(
225 rendered.getByText('data: This is fine :dog: :fire:'),
226 ).toBeInTheDocument()
227 expect(queryOpts.queryFn).toHaveBeenCalledTimes(1)
228 consoleMock.mockRestore()
229 })
230β
231 it('should not create a suspense waterfall if prefetch is fired', async () => {
232 const firstQueryOpts = {
233 queryKey: queryKey(),
234 queryFn: generateQueryFn('Prefetch is nice!'),
235 }
236β
237 const secondQueryOpts = {
238 queryKey: queryKey(),
239 queryFn: generateQueryFn('Prefetch is really nice!!'),
240 }
241β
242 const thirdQueryOpts = {
243 queryKey: queryKey(),
244 queryFn: generateQueryFn('Prefetch does not create waterfalls!!'),
245 }
246β
247 const Fallback = vi.fn().mockImplementation(() => <div>Loading...</div>)
248β
249 function App() {
250 usePrefetchQuery(firstQueryOpts)
251 usePrefetchQuery(secondQueryOpts)
252 usePrefetchQuery(thirdQueryOpts)
253β
254 return (
255 <Suspense fallback={<Fallback />}>
256 <Suspended queryOpts={firstQueryOpts}>
257 <Suspended queryOpts={secondQueryOpts}>
258 <Suspended queryOpts={thirdQueryOpts} />
259 </Suspended>
260 </Suspended>
261 </Suspense>
262 )
263 }
264β
265 const rendered = renderWithClient(queryClient, <App />)
266 expect(
267 queryClient.getQueryState(firstQueryOpts.queryKey)?.fetchStatus,
268 ).toBe('fetching')
269 expect(
270 queryClient.getQueryState(secondQueryOpts.queryKey)?.fetchStatus,
271 ).toBe('fetching')
272 expect(
273 queryClient.getQueryState(thirdQueryOpts.queryKey)?.fetchStatus,
274 ).toBe('fetching')
275 expect(rendered.getByText('Loading...')).toBeInTheDocument()
276 await act(async () => {
277 await vi.advanceTimersByTimeAsync(10)
278 })
279 expect(rendered.getByText('data: Prefetch is nice!')).toBeInTheDocument()
280 expect(
281 rendered.getByText('data: Prefetch is really nice!!'),
282 ).toBeInTheDocument()
283 expect(
284 rendered.getByText('data: Prefetch does not create waterfalls!!'),
285 ).toBeInTheDocument()
286 expect(Fallback).toHaveBeenCalledTimes(1)
287 expect(firstQueryOpts.queryFn).toHaveBeenCalledTimes(1)
288 expect(secondQueryOpts.queryFn).toHaveBeenCalledTimes(1)
289 expect(thirdQueryOpts.queryFn).toHaveBeenCalledTimes(1)
290 })
291})