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(11))
76 rendered.getByText('data: prefetchQuery')
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 rendered.getByText('data: The usePrefetchQuery hook is smart!')
103 expect(queryOpts.queryFn).not.toHaveBeenCalled()
104 })
105β
106 it('should let errors fall through and not refetch failed queries', async () => {
107 const consoleMock = vi.spyOn(console, 'error')
108 consoleMock.mockImplementation(() => undefined)
109 const queryFn = generateQueryFn('Not an error')
110β
111 const queryOpts = {
112 queryKey: queryKey(),
113 queryFn,
114 }
115β
116 queryFn.mockImplementationOnce(async () => {
117 await sleep(10)
118β
119 throw new Error('Oops! Server error!')
120 })
121β
122 function App() {
123 usePrefetchQuery(queryOpts)
124β
125 return (
126 <ErrorBoundary fallbackRender={() => <div>Oops!</div>}>
127 <React.Suspense fallback="Loading...">
128 <Suspended queryOpts={queryOpts} />
129 </React.Suspense>
130 </ErrorBoundary>
131 )
132 }
133β
134 queryClient.prefetchQuery(queryOpts)
135 await vi.advanceTimersByTimeAsync(10)
136 queryFn.mockClear()
137 const rendered = renderWithClient(queryClient, <App />)
138β
139 rendered.getByText('Oops!')
140 expect(rendered.queryByText('data: Not an error')).not.toBeInTheDocument()
141 expect(queryOpts.queryFn).not.toHaveBeenCalled()
142β
143 consoleMock.mockRestore()
144 })
145β
146 it('should not create an endless loop when using inside a suspense boundary', async () => {
147 const queryFn = generateQueryFn('prefetchedQuery')
148β
149 const queryOpts = {
150 queryKey: queryKey(),
151 queryFn,
152 }
153β
154 function Prefetch({ children }: { children: React.ReactNode }) {
155 usePrefetchQuery(queryOpts)
156 return <>{children}</>
157 }
158β
159 function App() {
160 return (
161 <React.Suspense>
162 <Prefetch>
163 <Suspended queryOpts={queryOpts} />
164 </Prefetch>
165 </React.Suspense>
166 )
167 }
168β
169 const rendered = renderWithClient(queryClient, <App />)
170 await act(() => vi.advanceTimersByTimeAsync(11))
171 rendered.getByText('data: prefetchedQuery')
172 expect(queryOpts.queryFn).toHaveBeenCalledTimes(1)
173 })
174β
175 it('should be able to recover from errors and try fetching again', async () => {
176 const consoleMock = vi.spyOn(console, 'error')
177 consoleMock.mockImplementation(() => undefined)
178 const queryFn = generateQueryFn('This is fine :dog: :fire:')
179β
180 const queryOpts = {
181 queryKey: queryKey(),
182 queryFn,
183 }
184β
185 queryFn.mockImplementationOnce(async () => {
186 await sleep(10)
187β
188 throw new Error('Oops! Server error!')
189 })
190β
191 function App() {
192 const { reset } = useQueryErrorResetBoundary()
193 usePrefetchQuery(queryOpts)
194β
195 return (
196 <ErrorBoundary
197 onReset={reset}
198 fallbackRender={({ resetErrorBoundary }) => (
199 <div>
200 <div>Oops!</div>
201 <button onClick={resetErrorBoundary}>Try again</button>
202 </div>
203 )}
204 >
205 <React.Suspense fallback="Loading...">
206 <Suspended queryOpts={queryOpts} />
207 </React.Suspense>
208 </ErrorBoundary>
209 )
210 }
211β
212 queryClient.prefetchQuery(queryOpts)
213 await vi.advanceTimersByTimeAsync(10)
214 queryFn.mockClear()
215β
216 const rendered = renderWithClient(queryClient, <App />)
217β
218 rendered.getByText('Oops!')
219 fireEvent.click(rendered.getByText('Try again'))
220 await act(() => vi.advanceTimersByTimeAsync(11))
221 rendered.getByText('data: This is fine :dog: :fire:')
222 expect(queryOpts.queryFn).toHaveBeenCalledTimes(1)
223 consoleMock.mockRestore()
224 })
225β
226 it('should not create a suspense waterfall if prefetch is fired', async () => {
227 const firstQueryOpts = {
228 queryKey: queryKey(),
229 queryFn: generateQueryFn('Prefetch is nice!'),
230 }
231β
232 const secondQueryOpts = {
233 queryKey: queryKey(),
234 queryFn: generateQueryFn('Prefetch is really nice!!'),
235 }
236β
237 const thirdQueryOpts = {
238 queryKey: queryKey(),
239 queryFn: generateQueryFn('Prefetch does not create waterfalls!!'),
240 }
241β
242 const Fallback = vi.fn().mockImplementation(() => <div>Loading...</div>)
243β
244 function App() {
245 usePrefetchQuery(firstQueryOpts)
246 usePrefetchQuery(secondQueryOpts)
247 usePrefetchQuery(thirdQueryOpts)
248β
249 return (
250 <React.Suspense fallback={<Fallback />}>
251 <Suspended queryOpts={firstQueryOpts}>
252 <Suspended queryOpts={secondQueryOpts}>
253 <Suspended queryOpts={thirdQueryOpts} />
254 </Suspended>
255 </Suspended>
256 </React.Suspense>
257 )
258 }
259β
260 const rendered = renderWithClient(queryClient, <App />)
261 expect(
262 queryClient.getQueryState(firstQueryOpts.queryKey)?.fetchStatus,
263 ).toBe('fetching')
264 expect(
265 queryClient.getQueryState(secondQueryOpts.queryKey)?.fetchStatus,
266 ).toBe('fetching')
267 expect(
268 queryClient.getQueryState(thirdQueryOpts.queryKey)?.fetchStatus,
269 ).toBe('fetching')
270 rendered.getByText('Loading...')
271 await act(() => vi.advanceTimersByTimeAsync(11))
272 rendered.getByText('data: Prefetch is nice!')
273 rendered.getByText('data: Prefetch is really nice!!')
274 rendered.getByText('data: Prefetch does not create waterfalls!!')
275 expect(Fallback).toHaveBeenCalledTimes(1)
276 expect(firstQueryOpts.queryFn).toHaveBeenCalledTimes(1)
277 expect(secondQueryOpts.queryFn).toHaveBeenCalledTimes(1)
278 expect(thirdQueryOpts.queryFn).toHaveBeenCalledTimes(1)
279 })
280})