Open History to see the last commit
1import { beforeAll, describe, expect, test, vi } from 'vitest'
2import * as React from 'react'
3import { render } from '@testing-library/react'
4β
5import * as coreModule from '@tanstack/query-core'
6import {
7 HydrationBoundary,
8 QueryCache,
9 QueryClient,
10 QueryClientProvider,
11 dehydrate,
12 useQuery,
13} from '..'
14import { createQueryClient, sleep } from './utils'
15β
16describe('React hydration', () => {
17 const fetchData: (value: string) => Promise<string> = (value) =>
18 new Promise((res) => setTimeout(() => res(value), 10))
19 const dataQuery: (key: [string]) => Promise<string> = (key) =>
20 fetchData(key[0])
21 let stringifiedState: string
22β
23 beforeAll(async () => {
24 const queryCache = new QueryCache()
25 const queryClient = createQueryClient({ queryCache })
26 await queryClient.prefetchQuery({
27 queryKey: ['string'],
28 queryFn: () => dataQuery(['stringCached']),
29 })
30 const dehydrated = dehydrate(queryClient)
31 stringifiedState = JSON.stringify(dehydrated)
32 queryClient.clear()
33 })
34β
35 test('should hydrate queries to the cache on context', async () => {
36 const dehydratedState = JSON.parse(stringifiedState)
37 const queryCache = new QueryCache()
38 const queryClient = createQueryClient({ queryCache })
39β
40 function Page() {
41 const { data } = useQuery({
42 queryKey: ['string'],
43 queryFn: () => dataQuery(['string']),
44 })
45 return (
46 <div>
47 <h1>{data}</h1>
48 </div>
49 )
50 }
51β
52 const rendered = render(
53 <QueryClientProvider client={queryClient}>
54 <HydrationBoundary state={dehydratedState}>
55 <Page />
56 </HydrationBoundary>
57 </QueryClientProvider>,
58 )
59β
60 await rendered.findByText('stringCached')
61 await rendered.findByText('string')
62 queryClient.clear()
63 })
64β
65 test('should hydrate queries to the cache on custom context', async () => {
66 const queryCacheOuter = new QueryCache()
67 const queryCacheInner = new QueryCache()
68β
69 const queryClientInner = new QueryClient({ queryCache: queryCacheInner })
70 const queryClientOuter = new QueryClient({ queryCache: queryCacheOuter })
71β
72 const dehydratedState = JSON.parse(stringifiedState)
73β
74 function Page() {
75 const { data } = useQuery({
76 queryKey: ['string'],
77 queryFn: () => dataQuery(['string']),
78 })
79 return (
80 <div>
81 <h1>{data}</h1>
82 </div>
83 )
84 }
85β
86 const rendered = render(
87 <QueryClientProvider client={queryClientOuter}>
88 <QueryClientProvider client={queryClientInner}>
89 <HydrationBoundary state={dehydratedState}>
90 <Page />
91 </HydrationBoundary>
92 </QueryClientProvider>
93 </QueryClientProvider>,
94 )
95β
96 await rendered.findByText('stringCached')
97 await rendered.findByText('string')
98β
99 queryClientInner.clear()
100 queryClientOuter.clear()
101 })
102β
103 describe('ReactQueryCacheProvider with hydration support', () => {
104 test('should hydrate new queries if queries change', async () => {
105 const dehydratedState = JSON.parse(stringifiedState)
106 const queryCache = new QueryCache()
107 const queryClient = createQueryClient({ queryCache })
108β
109 function Page({ queryKey }: { queryKey: [string] }) {
110 const { data } = useQuery({
111 queryKey,
112 queryFn: () => dataQuery(queryKey),
113 })
114 return (
115 <div>
116 <h1>{data}</h1>
117 </div>
118 )
119 }
120β
121 const rendered = render(
122 <QueryClientProvider client={queryClient}>
123 <HydrationBoundary state={dehydratedState}>
124 <Page queryKey={['string']} />
125 </HydrationBoundary>
126 </QueryClientProvider>,
127 )
128β
129 await rendered.findByText('string')
130β
131 const intermediateCache = new QueryCache()
132 const intermediateClient = createQueryClient({
133 queryCache: intermediateCache,
134 })
135 await intermediateClient.prefetchQuery({
136 queryKey: ['string'],
137 queryFn: () => dataQuery(['should change']),
138 })
139 await intermediateClient.prefetchQuery({
140 queryKey: ['added'],
141 queryFn: () => dataQuery(['added']),
142 })
143 const dehydrated = dehydrate(intermediateClient)
144 intermediateClient.clear()
145β
146 rendered.rerender(
147 <QueryClientProvider client={queryClient}>
148 <HydrationBoundary state={dehydrated}>
149 <Page queryKey={['string']} />
150 <Page queryKey={['added']} />
151 </HydrationBoundary>
152 </QueryClientProvider>,
153 )
154β
155 // Existing observer should not have updated at this point,
156 // as that would indicate a side effect in the render phase
157 rendered.getByText('string')
158 // New query data should be available immediately
159 rendered.getByText('added')
160β
161 await sleep(10)
162 // After effects phase has had time to run, the observer should have updated
163 expect(rendered.queryByText('string')).toBeNull()
164 rendered.getByText('should change')
165β
166 queryClient.clear()
167 })
168β
169 // When we hydrate in transitions that are later aborted, it could be
170 // confusing to both developers and users if we suddenly updated existing
171 // state on the screen (why did this update when it was not stale, nothing
172 // remounted, I didn't change tabs etc?).
173 // Any queries that does not exist in the cache yet can still be hydrated
174 // since they don't have any observers on the current page that would update.
175 test('should hydrate new but not existing queries if transition is aborted', async () => {
176 const initialDehydratedState = JSON.parse(stringifiedState)
177 const queryCache = new QueryCache()
178 const queryClient = createQueryClient({ queryCache })
179β
180 function Page({ queryKey }: { queryKey: [string] }) {
181 const { data } = useQuery({
182 queryKey,
183 queryFn: () => dataQuery(queryKey),
184 })
185 return (
186 <div>
187 <h1>{data}</h1>
188 </div>
189 )
190 }
191β
192 const rendered = render(
193 <QueryClientProvider client={queryClient}>
194 <HydrationBoundary state={initialDehydratedState}>
195 <Page queryKey={['string']} />
196 </HydrationBoundary>
197 </QueryClientProvider>,
198 )
199β
200 await rendered.findByText('string')
201β
202 const intermediateCache = new QueryCache()
203 const intermediateClient = createQueryClient({
204 queryCache: intermediateCache,
205 })
206 await intermediateClient.prefetchQuery({
207 queryKey: ['string'],
208 queryFn: () => dataQuery(['should not change']),
209 })
210 await intermediateClient.prefetchQuery({
211 queryKey: ['added'],
212 queryFn: () => dataQuery(['added']),
213 })
214 const newDehydratedState = dehydrate(intermediateClient)
215 intermediateClient.clear()
216β
217 function Thrower() {
218 throw new Promise(() => {
219 // Never resolve
220 })
221β
222 // @ts-expect-error
223 return null
224 }
225β
226 React.startTransition(() => {
227 rendered.rerender(
228 <React.Suspense fallback="loading">
229 <QueryClientProvider client={queryClient}>
230 <HydrationBoundary state={newDehydratedState}>
231 <Page queryKey={['string']} />
232 <Page queryKey={['added']} />
233 <Thrower />
234 </HydrationBoundary>
235 </QueryClientProvider>
236 </React.Suspense>,
237 )
238β
239 rendered.getByText('loading')
240 })
241β
242 React.startTransition(() => {
243 rendered.rerender(
244 <QueryClientProvider client={queryClient}>
245 <HydrationBoundary state={initialDehydratedState}>
246 <Page queryKey={['string']} />
247 <Page queryKey={['added']} />
248 </HydrationBoundary>
249 </QueryClientProvider>,
250 )
251β
252 // This query existed before the transition so it should stay the same
253 rendered.getByText('string')
254 expect(rendered.queryByText('should not change')).toBeNull()
255 // New query data should be available immediately because it was
256 // hydrated in the previous transition, even though the new dehydrated
257 // state did not contain it
258 rendered.getByText('added')
259 })
260β
261 await sleep(10)
262 // It should stay the same even after effects have had a chance to run
263 rendered.getByText('string')
264 expect(rendered.queryByText('should not change')).toBeNull()
265β
266 queryClient.clear()
267 })
268β
269 test('should hydrate queries to new cache if cache changes', async () => {
270 const dehydratedState = JSON.parse(stringifiedState)
271 const queryCache = new QueryCache()
272 const queryClient = createQueryClient({ queryCache })
273β
274 function Page() {
275 const { data } = useQuery({
276 queryKey: ['string'],
277 queryFn: () => dataQuery(['string']),
278 })
279 return (
280 <div>
281 <h1>{data}</h1>
282 </div>
283 )
284 }
285β
286 const rendered = render(
287 <QueryClientProvider client={queryClient}>
288 <HydrationBoundary state={dehydratedState}>
289 <Page />
290 </HydrationBoundary>
291 </QueryClientProvider>,
292 )
293β
294 await rendered.findByText('string')
295β
296 const newClientQueryCache = new QueryCache()
297 const newClientQueryClient = createQueryClient({
298 queryCache: newClientQueryCache,
299 })
300β
301 rendered.rerender(
302 <QueryClientProvider client={newClientQueryClient}>
303 <HydrationBoundary state={dehydratedState}>
304 <Page />
305 </HydrationBoundary>
306 </QueryClientProvider>,
307 )
308β
309 await sleep(10)
310 rendered.getByText('string')
311β
312 queryClient.clear()
313 newClientQueryClient.clear()
314 })
315 })
316β
317 test('should not hydrate queries if state is null', async () => {
318 const queryCache = new QueryCache()
319 const queryClient = createQueryClient({ queryCache })
320β
321 const hydrateSpy = vi.spyOn(coreModule, 'hydrate')
322β
323 function Page() {
324 return null
325 }
326β
327 render(
328 <QueryClientProvider client={queryClient}>
329 <HydrationBoundary state={null}>
330 <Page />
331 </HydrationBoundary>
332 </QueryClientProvider>,
333 )
334β
335 expect(hydrateSpy).toHaveBeenCalledTimes(0)
336β
337 hydrateSpy.mockRestore()
338 queryClient.clear()
339 })
340β
341 test('should not hydrate queries if state is undefined', async () => {
342 const queryCache = new QueryCache()
343 const queryClient = createQueryClient({ queryCache })
344β
345 const hydrateSpy = vi.spyOn(coreModule, 'hydrate')
346β
347 function Page() {
348 return null
349 }
350β
351 render(
352 <QueryClientProvider client={queryClient}>
353 <HydrationBoundary state={undefined}>
354 <Page />
355 </HydrationBoundary>
356 </QueryClientProvider>,
357 )
358β
359 expect(hydrateSpy).toHaveBeenCalledTimes(0)
360β
361 hydrateSpy.mockRestore()
362 queryClient.clear()
363 })
364})