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