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