Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2import * as React from 'react'
3import { render } from '@testing-library/react'
4import * as coreModule from '@tanstack/query-core'
5import { sleep } from '@tanstack/query-test-utils'
6import {
7 HydrationBoundary,
8 QueryClient,
9 QueryClientProvider,
10 dehydrate,
11 useQuery,
12} from '..'
13import type { hydrate } from '@tanstack/query-core'
14β
15describe('React hydration', () => {
16 let stringifiedState: string
17β
18 beforeEach(async () => {
19 vi.useFakeTimers()
20 const queryClient = new QueryClient()
21 queryClient.prefetchQuery({
22 queryKey: ['string'],
23 queryFn: () => sleep(10).then(() => ['stringCached']),
24 })
25 await vi.advanceTimersByTimeAsync(10)
26 const dehydrated = dehydrate(queryClient)
27 stringifiedState = JSON.stringify(dehydrated)
28 queryClient.clear()
29 })
30 afterEach(() => {
31 vi.useRealTimers()
32 })
33β
34 it('should hydrate queries to the cache on context', async () => {
35 const dehydratedState = JSON.parse(stringifiedState)
36 const queryClient = new QueryClient()
37β
38 function Page() {
39 const { data } = useQuery({
40 queryKey: ['string'],
41 queryFn: () => sleep(20).then(() => ['string']),
42 })
43 return (
44 <div>
45 <h1>{data}</h1>
46 </div>
47 )
48 }
49β
50 const rendered = render(
51 <QueryClientProvider client={queryClient}>
52 <HydrationBoundary state={dehydratedState}>
53 <Page />
54 </HydrationBoundary>
55 </QueryClientProvider>,
56 )
57β
58 expect(rendered.getByText('stringCached')).toBeInTheDocument()
59 await vi.advanceTimersByTimeAsync(21)
60 expect(rendered.getByText('string')).toBeInTheDocument()
61 queryClient.clear()
62 })
63β
64 it('should hydrate queries to the cache on custom context', async () => {
65 const queryClientInner = new QueryClient()
66 const queryClientOuter = new QueryClient()
67β
68 const dehydratedState = JSON.parse(stringifiedState)
69β
70 function Page() {
71 const { data } = useQuery({
72 queryKey: ['string'],
73 queryFn: () => sleep(20).then(() => ['string']),
74 })
75 return (
76 <div>
77 <h1>{data}</h1>
78 </div>
79 )
80 }
81β
82 const rendered = render(
83 <QueryClientProvider client={queryClientOuter}>
84 <QueryClientProvider client={queryClientInner}>
85 <HydrationBoundary state={dehydratedState}>
86 <Page />
87 </HydrationBoundary>
88 </QueryClientProvider>
89 </QueryClientProvider>,
90 )
91β
92 expect(rendered.getByText('stringCached')).toBeInTheDocument()
93 await vi.advanceTimersByTimeAsync(21)
94 expect(rendered.getByText('string')).toBeInTheDocument()
95β
96 queryClientInner.clear()
97 queryClientOuter.clear()
98 })
99β
100 describe('ReactQueryCacheProvider with hydration support', () => {
101 it('should hydrate new queries if queries change', async () => {
102 const dehydratedState = JSON.parse(stringifiedState)
103 const queryClient = new QueryClient()
104β
105 function Page({ queryKey }: { queryKey: [string] }) {
106 const { data } = useQuery({
107 queryKey,
108 queryFn: () => sleep(20).then(() => queryKey),
109 })
110 return (
111 <div>
112 <h1>{data}</h1>
113 </div>
114 )
115 }
116β
117 const rendered = render(
118 <QueryClientProvider client={queryClient}>
119 <HydrationBoundary state={dehydratedState}>
120 <Page queryKey={['string']} />
121 </HydrationBoundary>
122 </QueryClientProvider>,
123 )
124β
125 expect(rendered.getByText('stringCached')).toBeInTheDocument()
126 await vi.advanceTimersByTimeAsync(21)
127 expect(rendered.getByText('string')).toBeInTheDocument()
128β
129 const intermediateClient = new QueryClient()
130β
131 intermediateClient.prefetchQuery({
132 queryKey: ['string'],
133 queryFn: () => sleep(20).then(() => ['should change']),
134 })
135 intermediateClient.prefetchQuery({
136 queryKey: ['added'],
137 queryFn: () => sleep(20).then(() => ['added']),
138 })
139 await vi.advanceTimersByTimeAsync(20)
140 const dehydrated = dehydrate(intermediateClient)
141 intermediateClient.clear()
142β
143 rendered.rerender(
144 <QueryClientProvider client={queryClient}>
145 <HydrationBoundary state={dehydrated}>
146 <Page queryKey={['string']} />
147 <Page queryKey={['added']} />
148 </HydrationBoundary>
149 </QueryClientProvider>,
150 )
151β
152 // Existing observer should not have updated at this point,
153 // as that would indicate a side effect in the render phase
154 expect(rendered.getByText('string')).toBeInTheDocument()
155 // New query data should be available immediately
156 expect(rendered.getByText('added')).toBeInTheDocument()
157β
158 await vi.advanceTimersByTimeAsync(0)
159 // After effects phase has had time to run, the observer should have updated
160 expect(rendered.queryByText('string')).not.toBeInTheDocument()
161 expect(rendered.getByText('should change')).toBeInTheDocument()
162β
163 queryClient.clear()
164 })
165β
166 // When we hydrate in transitions that are later aborted, it could be
167 // confusing to both developers and users if we suddenly updated existing
168 // state on the screen (why did this update when it was not stale, nothing
169 // remounted, I didn't change tabs etc?).
170 // Any queries that does not exist in the cache yet can still be hydrated
171 // since they don't have any observers on the current page that would update.
172 it('should hydrate new but not existing queries if transition is aborted', async () => {
173 const initialDehydratedState = JSON.parse(stringifiedState)
174 const queryClient = new QueryClient()
175β
176 function Page({ queryKey }: { queryKey: [string] }) {
177 const { data } = useQuery({
178 queryKey,
179 queryFn: () => sleep(20).then(() => queryKey),
180 })
181 return (
182 <div>
183 <h1>{data}</h1>
184 </div>
185 )
186 }
187β
188 const rendered = render(
189 <QueryClientProvider client={queryClient}>
190 <HydrationBoundary state={initialDehydratedState}>
191 <Page queryKey={['string']} />
192 </HydrationBoundary>
193 </QueryClientProvider>,
194 )
195β
196 expect(rendered.getByText('stringCached')).toBeInTheDocument()
197 await vi.advanceTimersByTimeAsync(21)
198 expect(rendered.getByText('string')).toBeInTheDocument()
199β
200 const intermediateClient = new QueryClient()
201 intermediateClient.prefetchQuery({
202 queryKey: ['string'],
203 queryFn: () => sleep(20).then(() => ['should not change']),
204 })
205 intermediateClient.prefetchQuery({
206 queryKey: ['added'],
207 queryFn: () => sleep(20).then(() => ['added']),
208 })
209 await vi.advanceTimersByTimeAsync(20)
210β
211 const newDehydratedState = dehydrate(intermediateClient)
212 intermediateClient.clear()
213β
214 function Thrower(): never {
215 throw new Promise(() => {
216 // Never resolve
217 })
218 }
219β
220 React.startTransition(() => {
221 rendered.rerender(
222 <React.Suspense fallback="loading">
223 <QueryClientProvider client={queryClient}>
224 <HydrationBoundary state={newDehydratedState}>
225 <Page queryKey={['string']} />
226 <Page queryKey={['added']} />
227 <Thrower />
228 </HydrationBoundary>
229 </QueryClientProvider>
230 </React.Suspense>,
231 )
232β
233 expect(rendered.getByText('loading')).toBeInTheDocument()
234 })
235β
236 React.startTransition(() => {
237 rendered.rerender(
238 <QueryClientProvider client={queryClient}>
239 <HydrationBoundary state={initialDehydratedState}>
240 <Page queryKey={['string']} />
241 <Page queryKey={['added']} />
242 </HydrationBoundary>
243 </QueryClientProvider>,
244 )
245β
246 // This query existed before the transition so it should stay the same
247 expect(rendered.getByText('string')).toBeInTheDocument()
248 expect(
249 rendered.queryByText('should not change'),
250 ).not.toBeInTheDocument()
251 // New query data should be available immediately because it was
252 // hydrated in the previous transition, even though the new dehydrated
253 // state did not contain it
254 expect(rendered.getByText('added')).toBeInTheDocument()
255 })
256β
257 await vi.advanceTimersByTimeAsync(20)
258 // It should stay the same even after effects have had a chance to run
259 expect(rendered.getByText('string')).toBeInTheDocument()
260 expect(rendered.queryByText('should not change')).not.toBeInTheDocument()
261β
262 queryClient.clear()
263 })
264β
265 it('should hydrate queries to new cache if cache changes', async () => {
266 const dehydratedState = JSON.parse(stringifiedState)
267 const queryClient = new QueryClient()
268β
269 function Page() {
270 const { data } = useQuery({
271 queryKey: ['string'],
272 queryFn: () => sleep(20).then(() => ['string']),
273 })
274 return (
275 <div>
276 <h1>{data}</h1>
277 </div>
278 )
279 }
280β
281 const rendered = render(
282 <QueryClientProvider client={queryClient}>
283 <HydrationBoundary state={dehydratedState}>
284 <Page />
285 </HydrationBoundary>
286 </QueryClientProvider>,
287 )
288β
289 expect(rendered.getByText('stringCached')).toBeInTheDocument()
290 await vi.advanceTimersByTimeAsync(21)
291 expect(rendered.getByText('string')).toBeInTheDocument()
292 const newClientQueryClient = new QueryClient()
293β
294 rendered.rerender(
295 <QueryClientProvider client={newClientQueryClient}>
296 <HydrationBoundary state={dehydratedState}>
297 <Page />
298 </HydrationBoundary>
299 </QueryClientProvider>,
300 )
301β
302 await vi.advanceTimersByTimeAsync(20)
303 expect(rendered.getByText('string')).toBeInTheDocument()
304β
305 queryClient.clear()
306 newClientQueryClient.clear()
307 })
308 })
309β
310 it('should not hydrate queries if state is null', async () => {
311 const queryClient = new QueryClient()
312β
313 const hydrateSpy = vi.spyOn(coreModule, 'hydrate')
314β
315 function Page() {
316 return null
317 }
318β
319 render(
320 <QueryClientProvider client={queryClient}>
321 <HydrationBoundary state={null}>
322 <Page />
323 </HydrationBoundary>
324 </QueryClientProvider>,
325 )
326β
327 await Promise.all(
328 Array.from({ length: 1000 }).map(async (_, index) => {
329 await vi.advanceTimersByTimeAsync(index)
330 expect(hydrateSpy).toHaveBeenCalledTimes(0)
331 }),
332 )
333β
334 hydrateSpy.mockRestore()
335 queryClient.clear()
336 })
337β
338 it('should not hydrate queries if state is undefined', async () => {
339 const queryClient = new QueryClient()
340β
341 const hydrateSpy = vi.spyOn(coreModule, 'hydrate')
342β
343 function Page() {
344 return null
345 }
346β
347 render(
348 <QueryClientProvider client={queryClient}>
349 <HydrationBoundary state={undefined}>
350 <Page />
351 </HydrationBoundary>
352 </QueryClientProvider>,
353 )
354β
355 await vi.advanceTimersByTimeAsync(0)
356 expect(hydrateSpy).toHaveBeenCalledTimes(0)
357β
358 hydrateSpy.mockRestore()
359 queryClient.clear()
360 })
361β
362 it('should not hydrate queries if state is not an object', async () => {
363 const queryClient = new QueryClient()
364β
365 const hydrateSpy = vi.spyOn(coreModule, 'hydrate')
366β
367 function Page() {
368 return null
369 }
370β
371 render(
372 <QueryClientProvider client={queryClient}>
373 <HydrationBoundary state={'invalid-state' as any}>
374 <Page />
375 </HydrationBoundary>
376 </QueryClientProvider>,
377 )
378β
379 await vi.advanceTimersByTimeAsync(0)
380 expect(hydrateSpy).toHaveBeenCalledTimes(0)
381β
382 hydrateSpy.mockRestore()
383 queryClient.clear()
384 })
385β
386 it('should handle state without queries property gracefully', async () => {
387 const queryClient = new QueryClient()
388β
389 const hydrateSpy = vi.spyOn(coreModule, 'hydrate')
390β
391 function Page() {
392 return null
393 }
394β
395 render(
396 <QueryClientProvider client={queryClient}>
397 <HydrationBoundary state={{} as any}>
398 <Page />
399 </HydrationBoundary>
400 </QueryClientProvider>,
401 )
402β
403 await vi.advanceTimersByTimeAsync(0)
404 expect(hydrateSpy).toHaveBeenCalledTimes(0)
405β
406 hydrateSpy.mockRestore()
407 queryClient.clear()
408 })
409β
410 // https://github.com/TanStack/query/issues/8677
411 it('should not infinite loop when hydrating promises that resolve to errors', async () => {
412 const originalHydrate = coreModule.hydrate
413 const hydrateSpy = vi.spyOn(coreModule, 'hydrate')
414 let hydrationCount = 0
415 hydrateSpy.mockImplementation((...args: Parameters<typeof hydrate>) => {
416 hydrationCount++
417 // Arbitrary number
418 if (hydrationCount > 10) {
419 // This is a rough way to detect it. Calling hydrate multiple times with
420 // the same data is usually fine, but in this case it indicates the
421 // logic in HydrationBoundary is not working as expected.
422 throw new Error('Too many hydrations detected')
423 }
424 return originalHydrate(...args)
425 })
426β
427 // For the bug to trigger, there needs to already be a query in the cache,
428 // with a dataUpdatedAt earlier than the dehydratedAt of the next query
429 const clientQueryClient = new QueryClient()
430 clientQueryClient.prefetchQuery({
431 queryKey: ['promise'],
432 queryFn: () => sleep(20).then(() => 'existing'),
433 })
434 await vi.advanceTimersByTimeAsync(20)
435β
436 const prefetchQueryClient = new QueryClient({
437 defaultOptions: {
438 dehydrate: {
439 shouldDehydrateQuery: () => true,
440 },
441 },
442 })
443 prefetchQueryClient.prefetchQuery({
444 queryKey: ['promise'],
445 queryFn: () =>
446 sleep(10).then(() => Promise.reject(new Error('Query failed'))),
447 })
448β
449 const dehydratedState = dehydrate(prefetchQueryClient)
450β
451 // Mimic what React/our synchronous thenable does for already rejected promises
452 // @ts-expect-error
453 dehydratedState.queries[0].promise.status = 'failure'
454β
455 function Page() {
456 const { data } = useQuery({
457 queryKey: ['promise'],
458 queryFn: () => sleep(20).then(() => ['new']),
459 })
460 return (
461 <div>
462 <h1>{data}</h1>
463 </div>
464 )
465 }
466β
467 const rendered = render(
468 <QueryClientProvider client={clientQueryClient}>
469 <HydrationBoundary state={dehydratedState}>
470 <Page />
471 </HydrationBoundary>
472 </QueryClientProvider>,
473 )
474β
475 expect(rendered.getByText('existing')).toBeInTheDocument()
476 await vi.advanceTimersByTimeAsync(21)
477 expect(rendered.getByText('new')).toBeInTheDocument()
478β
479 hydrateSpy.mockRestore()
480 prefetchQueryClient.clear()
481 clientQueryClient.clear()
482 })
483β
484 it('should not refetch when query has enabled set to false', async () => {
485 const queryFn = vi.fn()
486 const queryClient = new QueryClient()
487β
488 function Page() {
489 const { data } = useQuery({
490 queryKey: ['string'],
491 queryFn,
492 enabled: false,
493 })
494 return <div>{JSON.stringify(data)}</div>
495 }
496β
497 const rendered = render(
498 <QueryClientProvider client={queryClient}>
499 <HydrationBoundary state={JSON.parse(stringifiedState)}>
500 <Page />
501 </HydrationBoundary>
502 </QueryClientProvider>,
503 )
504β
505 expect(rendered.getByText('["stringCached"]')).toBeInTheDocument()
506β
507 await vi.advanceTimersByTimeAsync(11)
508 expect(queryFn).toHaveBeenCalledTimes(0)
509 expect(rendered.getByText('["stringCached"]')).toBeInTheDocument()
510β
511 queryClient.clear()
512 })
513β
514 it('should not refetch when query has staleTime set to Infinity', async () => {
515 const queryFn = vi.fn()
516 const queryClient = new QueryClient()
517β
518 function Page() {
519 const { data } = useQuery({
520 queryKey: ['string'],
521 queryFn,
522 staleTime: Infinity,
523 })
524 return <div>{JSON.stringify(data)}</div>
525 }
526β
527 const rendered = render(
528 <QueryClientProvider client={queryClient}>
529 <HydrationBoundary state={JSON.parse(stringifiedState)}>
530 <Page />
531 </HydrationBoundary>
532 </QueryClientProvider>,
533 )
534β
535 expect(rendered.getByText('["stringCached"]')).toBeInTheDocument()
536β
537 await vi.advanceTimersByTimeAsync(11)
538 expect(queryFn).toHaveBeenCalledTimes(0)
539 expect(rendered.getByText('["stringCached"]')).toBeInTheDocument()
540β
541 queryClient.clear()
542 })
543})