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

usePrefetchQuery.test.tsx

291 lines8.2 KB

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