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

usePrefetchQuery.test.tsx

288 lines8.1 KB

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