Open History to see the last commit
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})