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

usePrefetchQuery.test.tsx

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