Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

HydrationBoundary.test.tsx

558 lines16.3 KB

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​
165 await vi.advanceTimersByTimeAsync(0)
166 // After effects phase has had time to run, the observer should have updated
167 expect(rendered.queryByText('string')).not.toBeInTheDocument()
168 expect(rendered.getByText('should change')).toBeInTheDocument()
169​
170 queryClient.clear()
171 })
172​
173 // When we hydrate in transitions that are later aborted, it could be
174 // confusing to both developers and users if we suddenly updated existing
175 // state on the screen (why did this update when it was not stale, nothing
176 // remounted, I didn't change tabs etc?).
177 // Any queries that does not exist in the cache yet can still be hydrated
178 // since they don't have any observers on the current page that would update.
179 it('should hydrate new but not existing queries if transition is aborted', async () => {
180 const initialDehydratedState = JSON.parse(stringifiedState)
181 const queryClient = new QueryClient()
182​
183 function Page({ queryKey }: { queryKey: [string] }) {
184 const { data } = useQuery({
185 queryKey,
186 queryFn: () => sleep(20).then(() => queryKey),
187 })
188 return (
189 <div>
190 <h1>{data}</h1>
191 </div>
192 )
193 }
194​
195 const rendered = render(
196 <QueryClientProvider client={queryClient}>
197 <HydrationBoundary state={initialDehydratedState}>
198 <Page queryKey={['string']} />
199 </HydrationBoundary>
200 </QueryClientProvider>,
201 )
202​
203 expect(rendered.getByText('stringCached')).toBeInTheDocument()
204 await vi.advanceTimersByTimeAsync(21)
205 expect(rendered.getByText('string')).toBeInTheDocument()
206​
207 const intermediateClient = new QueryClient()
208 void intermediateClient
209 .query({
210 queryKey: ['string'],
211 queryFn: () => sleep(20).then(() => ['should not change']),
212 })
213 .catch(noop)
214 void intermediateClient
215 .query({
216 queryKey: ['added'],
217 queryFn: () => sleep(20).then(() => ['added']),
218 })
219 .catch(noop)
220 await vi.advanceTimersByTimeAsync(20)
221​
222 const newDehydratedState = dehydrate(intermediateClient)
223 intermediateClient.clear()
224​
225 function Thrower(): never {
226 throw new Promise(() => {
227 // Never resolve
228 })
229 }
230​
231 React.startTransition(() => {
232 rendered.rerender(
233 <React.Suspense fallback="loading">
234 <QueryClientProvider client={queryClient}>
235 <HydrationBoundary state={newDehydratedState}>
236 <Page queryKey={['string']} />
237 <Page queryKey={['added']} />
238 <Thrower />
239 </HydrationBoundary>
240 </QueryClientProvider>
241 </React.Suspense>,
242 )
243​
244 expect(rendered.getByText('loading')).toBeInTheDocument()
245 })
246​
247 React.startTransition(() => {
248 rendered.rerender(
249 <QueryClientProvider client={queryClient}>
250 <HydrationBoundary state={initialDehydratedState}>
251 <Page queryKey={['string']} />
252 <Page queryKey={['added']} />
253 </HydrationBoundary>
254 </QueryClientProvider>,
255 )
256​
257 // This query existed before the transition so it should stay the same
258 expect(rendered.getByText('string')).toBeInTheDocument()
259 expect(
260 rendered.queryByText('should not change'),
261 ).not.toBeInTheDocument()
262 // New query data should be available immediately because it was
263 // hydrated in the previous transition, even though the new dehydrated
264 // state did not contain it
265 expect(rendered.getByText('added')).toBeInTheDocument()
266 })
267​
268 await vi.advanceTimersByTimeAsync(20)
269 // It should stay the same even after effects have had a chance to run
270 expect(rendered.getByText('string')).toBeInTheDocument()
271 expect(rendered.queryByText('should not change')).not.toBeInTheDocument()
272​
273 queryClient.clear()
274 })
275​
276 it('should hydrate queries to new cache if cache changes', async () => {
277 const dehydratedState = JSON.parse(stringifiedState)
278 const queryClient = new QueryClient()
279​
280 function Page() {
281 const { data } = useQuery({
282 queryKey: ['string'],
283 queryFn: () => sleep(20).then(() => ['string']),
284 })
285 return (
286 <div>
287 <h1>{data}</h1>
288 </div>
289 )
290 }
291​
292 const rendered = render(
293 <QueryClientProvider client={queryClient}>
294 <HydrationBoundary state={dehydratedState}>
295 <Page />
296 </HydrationBoundary>
297 </QueryClientProvider>,
298 )
299​
300 expect(rendered.getByText('stringCached')).toBeInTheDocument()
301 await vi.advanceTimersByTimeAsync(21)
302 expect(rendered.getByText('string')).toBeInTheDocument()
303 const newClientQueryClient = new QueryClient()
304​
305 rendered.rerender(
306 <QueryClientProvider client={newClientQueryClient}>
307 <HydrationBoundary state={dehydratedState}>
308 <Page />
309 </HydrationBoundary>
310 </QueryClientProvider>,
311 )
312​
313 await vi.advanceTimersByTimeAsync(20)
314 expect(rendered.getByText('string')).toBeInTheDocument()
315​
316 queryClient.clear()
317 newClientQueryClient.clear()
318 })
319 })
320​
321 it('should not hydrate queries if state is null', async () => {
322 const queryClient = new QueryClient()
323​
324 const hydrateSpy = vi.spyOn(coreModule, 'hydrate')
325​
326 function Page() {
327 return null
328 }
329​
330 render(
331 <QueryClientProvider client={queryClient}>
332 <HydrationBoundary state={null}>
333 <Page />
334 </HydrationBoundary>
335 </QueryClientProvider>,
336 )
337​
338 await Promise.all(
339 Array.from({ length: 1000 }).map(async (_, index) => {
340 await vi.advanceTimersByTimeAsync(index)
341 expect(hydrateSpy).toHaveBeenCalledTimes(0)
342 }),
343 )
344​
345 hydrateSpy.mockRestore()
346 queryClient.clear()
347 })
348​
349 it('should not hydrate queries if state is undefined', async () => {
350 const queryClient = new QueryClient()
351​
352 const hydrateSpy = vi.spyOn(coreModule, 'hydrate')
353​
354 function Page() {
355 return null
356 }
357​
358 render(
359 <QueryClientProvider client={queryClient}>
360 <HydrationBoundary state={undefined}>
361 <Page />
362 </HydrationBoundary>
363 </QueryClientProvider>,
364 )
365​
366 await vi.advanceTimersByTimeAsync(0)
367 expect(hydrateSpy).toHaveBeenCalledTimes(0)
368​
369 hydrateSpy.mockRestore()
370 queryClient.clear()
371 })
372​
373 it('should not hydrate queries if state is not an object', async () => {
374 const queryClient = new QueryClient()
375​
376 const hydrateSpy = vi.spyOn(coreModule, 'hydrate')
377​
378 function Page() {
379 return null
380 }
381​
382 render(
383 <QueryClientProvider client={queryClient}>
384 <HydrationBoundary state={'invalid-state' as any}>
385 <Page />
386 </HydrationBoundary>
387 </QueryClientProvider>,
388 )
389​
390 await vi.advanceTimersByTimeAsync(0)
391 expect(hydrateSpy).toHaveBeenCalledTimes(0)
392​
393 hydrateSpy.mockRestore()
394 queryClient.clear()
395 })
396​
397 it('should handle state without queries property gracefully', async () => {
398 const queryClient = new QueryClient()
399​
400 const hydrateSpy = vi.spyOn(coreModule, 'hydrate')
401​
402 function Page() {
403 return null
404 }
405​
406 render(
407 <QueryClientProvider client={queryClient}>
408 <HydrationBoundary state={{} as any}>
409 <Page />
410 </HydrationBoundary>
411 </QueryClientProvider>,
412 )
413​
414 await vi.advanceTimersByTimeAsync(0)
415 expect(hydrateSpy).toHaveBeenCalledTimes(0)
416​
417 hydrateSpy.mockRestore()
418 queryClient.clear()
419 })
420​
421 // https://github.com/TanStack/query/issues/8677
422 it('should not infinite loop when hydrating promises that resolve to errors', async () => {
423 const originalHydrate = coreModule.hydrate
424 const hydrateSpy = vi.spyOn(coreModule, 'hydrate')
425 let hydrationCount = 0
426 hydrateSpy.mockImplementation((...args: Parameters<typeof hydrate>) => {
427 hydrationCount++
428 // Arbitrary number
429 if (hydrationCount > 10) {
430 // This is a rough way to detect it. Calling hydrate multiple times with
431 // the same data is usually fine, but in this case it indicates the
432 // logic in HydrationBoundary is not working as expected.
433 throw new Error('Too many hydrations detected')
434 }
435 return originalHydrate(...args)
436 })
437​
438 // For the bug to trigger, there needs to already be a query in the cache,
439 // with a dataUpdatedAt earlier than the dehydratedAt of the next query
440 const clientQueryClient = new QueryClient()
441 void clientQueryClient
442 .query({
443 queryKey: ['promise'],
444 queryFn: () => sleep(20).then(() => 'existing'),
445 })
446 .catch(noop)
447 await vi.advanceTimersByTimeAsync(20)
448​
449 const prefetchQueryClient = new QueryClient({
450 defaultOptions: {
451 dehydrate: {
452 shouldDehydrateQuery: () => true,
453 },
454 },
455 })
456 void prefetchQueryClient
457 .query({
458 queryKey: ['promise'],
459 queryFn: () =>
460 sleep(10).then(() => Promise.reject(new Error('Query failed'))),
461 })
462 .catch(noop)
463​
464 const dehydratedState = dehydrate(prefetchQueryClient)
465​
466 // Mimic what React/our synchronous thenable does for already rejected promises
467 // @ts-expect-error
468 dehydratedState.queries[0].promise.status = 'failure'
469​
470 function Page() {
471 const { data } = useQuery({
472 queryKey: ['promise'],
473 queryFn: () => sleep(20).then(() => ['new']),
474 })
475 return (
476 <div>
477 <h1>{data}</h1>
478 </div>
479 )
480 }
481​
482 const rendered = render(
483 <QueryClientProvider client={clientQueryClient}>
484 <HydrationBoundary state={dehydratedState}>
485 <Page />
486 </HydrationBoundary>
487 </QueryClientProvider>,
488 )
489​
490 expect(rendered.getByText('existing')).toBeInTheDocument()
491 await vi.advanceTimersByTimeAsync(21)
492 expect(rendered.getByText('new')).toBeInTheDocument()
493​
494 hydrateSpy.mockRestore()
495 prefetchQueryClient.clear()
496 clientQueryClient.clear()
497 })
498​
499 it('should not refetch when query has enabled set to false', async () => {
500 const queryFn = vi.fn()
501 const queryClient = new QueryClient()
502​
503 function Page() {
504 const { data } = useQuery({
505 queryKey: ['string'],
506 queryFn,
507 enabled: false,
508 })
509 return <div>{JSON.stringify(data)}</div>
510 }
511​
512 const rendered = render(
513 <QueryClientProvider client={queryClient}>
514 <HydrationBoundary state={JSON.parse(stringifiedState)}>
515 <Page />
516 </HydrationBoundary>
517 </QueryClientProvider>,
518 )
519​
520 expect(rendered.getByText('["stringCached"]')).toBeInTheDocument()
521​
522 await vi.advanceTimersByTimeAsync(11)
523 expect(queryFn).toHaveBeenCalledTimes(0)
524 expect(rendered.getByText('["stringCached"]')).toBeInTheDocument()
525​
526 queryClient.clear()
527 })
528​
529 it('should not refetch when query has staleTime set to Infinity', async () => {
530 const queryFn = vi.fn()
531 const queryClient = new QueryClient()
532​
533 function Page() {
534 const { data } = useQuery({
535 queryKey: ['string'],
536 queryFn,
537 staleTime: Infinity,
538 })
539 return <div>{JSON.stringify(data)}</div>
540 }
541​
542 const rendered = render(
543 <QueryClientProvider client={queryClient}>
544 <HydrationBoundary state={JSON.parse(stringifiedState)}>
545 <Page />
546 </HydrationBoundary>
547 </QueryClientProvider>,
548 )
549​
550 expect(rendered.getByText('["stringCached"]')).toBeInTheDocument()
551​
552 await vi.advanceTimersByTimeAsync(11)
553 expect(queryFn).toHaveBeenCalledTimes(0)
554 expect(rendered.getByText('["stringCached"]')).toBeInTheDocument()
555​
556 queryClient.clear()
557 })
558})