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

HydrationBoundary.test.tsx

551 lines16.2 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​
34 afterEach(() => {
35 vi.useRealTimers()
36 })
37​
38 it('should hydrate queries to the cache on context', async () => {
39 const dehydratedState = JSON.parse(stringifiedState)
40 const queryClient = new QueryClient()
41​
42 function Page() {
43 const { data } = useQuery({
44 queryKey: ['string'],
45 queryFn: () => sleep(20).then(() => ['string']),
46 })
47 return (
48 <div>
49 <h1>{data}</h1>
50 </div>
51 )
52 }
53​
54 const rendered = render(
55 <QueryClientProvider client={queryClient}>
56 <HydrationBoundary state={dehydratedState}>
57 <Page />
58 </HydrationBoundary>
59 </QueryClientProvider>,
60 )
61​
62 expect(rendered.getByText('stringCached')).toBeInTheDocument()
63 await vi.advanceTimersByTimeAsync(21)
64 expect(rendered.getByText('string')).toBeInTheDocument()
65 queryClient.clear()
66 })
67​
68 it('should hydrate queries to the cache on custom context', async () => {
69 const queryClientInner = new QueryClient()
70 const queryClientOuter = new QueryClient()
71​
72 const dehydratedState = JSON.parse(stringifiedState)
73​
74 function Page() {
75 const { data } = useQuery({
76 queryKey: ['string'],
77 queryFn: () => sleep(20).then(() => ['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 expect(rendered.getByText('stringCached')).toBeInTheDocument()
97 await vi.advanceTimersByTimeAsync(21)
98 expect(rendered.getByText('string')).toBeInTheDocument()
99​
100 queryClientInner.clear()
101 queryClientOuter.clear()
102 })
103​
104 describe('ReactQueryCacheProvider with hydration support', () => {
105 it('should hydrate new queries if queries change', async () => {
106 const dehydratedState = JSON.parse(stringifiedState)
107 const queryClient = new QueryClient()
108​
109 function Page({ queryKey }: { queryKey: [string] }) {
110 const { data } = useQuery({
111 queryKey,
112 queryFn: () => sleep(20).then(() => 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 expect(rendered.getByText('stringCached')).toBeInTheDocument()
130 await vi.advanceTimersByTimeAsync(21)
131 expect(rendered.getByText('string')).toBeInTheDocument()
132​
133 const intermediateClient = new QueryClient()
134​
135 void intermediateClient
136 .query({
137 queryKey: ['string'],
138 queryFn: () => sleep(20).then(() => ['should change']),
139 })
140 .catch(noop)
141 void intermediateClient
142 .query({
143 queryKey: ['added'],
144 queryFn: () => sleep(20).then(() => ['added']),
145 })
146 .catch(noop)
147 await vi.advanceTimersByTimeAsync(20)
148 const dehydrated = dehydrate(intermediateClient)
149 intermediateClient.clear()
150​
151 rendered.rerender(
152 <QueryClientProvider client={queryClient}>
153 <HydrationBoundary state={dehydrated}>
154 <Page queryKey={['string']} />
155 <Page queryKey={['added']} />
156 </HydrationBoundary>
157 </QueryClientProvider>,
158 )
159​
160 // Existing observer should not have updated at this point,
161 // as that would indicate a side effect in the render phase
162 expect(rendered.getByText('string')).toBeInTheDocument()
163 // New query data should be available immediately
164 expect(rendered.getByText('added')).toBeInTheDocument()
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 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 queryClient.clear()
369 })
370​
371 it('should not hydrate queries if state is not an object', async () => {
372 const queryClient = new QueryClient()
373​
374 const hydrateSpy = vi.spyOn(coreModule, 'hydrate')
375​
376 function Page() {
377 return null
378 }
379​
380 render(
381 <QueryClientProvider client={queryClient}>
382 <HydrationBoundary state={'invalid-state' as any}>
383 <Page />
384 </HydrationBoundary>
385 </QueryClientProvider>,
386 )
387​
388 await vi.advanceTimersByTimeAsync(0)
389 expect(hydrateSpy).toHaveBeenCalledTimes(0)
390​
391 queryClient.clear()
392 })
393​
394 it('should handle state without queries property gracefully', async () => {
395 const queryClient = new QueryClient()
396​
397 const hydrateSpy = vi.spyOn(coreModule, 'hydrate')
398​
399 function Page() {
400 return null
401 }
402​
403 render(
404 <QueryClientProvider client={queryClient}>
405 <HydrationBoundary state={{} as any}>
406 <Page />
407 </HydrationBoundary>
408 </QueryClientProvider>,
409 )
410​
411 await vi.advanceTimersByTimeAsync(0)
412 expect(hydrateSpy).toHaveBeenCalledTimes(0)
413​
414 queryClient.clear()
415 })
416​
417 // https://github.com/TanStack/query/issues/8677
418 it('should not infinite loop when hydrating promises that resolve to errors', async () => {
419 const originalHydrate = coreModule.hydrate
420 const hydrateSpy = vi.spyOn(coreModule, 'hydrate')
421 let hydrationCount = 0
422 hydrateSpy.mockImplementation((...args: Parameters<typeof hydrate>) => {
423 hydrationCount++
424 // Arbitrary number
425 if (hydrationCount > 10) {
426 // This is a rough way to detect it. Calling hydrate multiple times with
427 // the same data is usually fine, but in this case it indicates the
428 // logic in HydrationBoundary is not working as expected.
429 throw new Error('Too many hydrations detected')
430 }
431 return originalHydrate(...args)
432 })
433​
434 // For the bug to trigger, there needs to already be a query in the cache,
435 // with a dataUpdatedAt earlier than the dehydratedAt of the next query
436 const clientQueryClient = new QueryClient()
437 void clientQueryClient
438 .query({
439 queryKey: ['promise'],
440 queryFn: () => sleep(20).then(() => 'existing'),
441 })
442 .catch(noop)
443 await vi.advanceTimersByTimeAsync(20)
444​
445 const prefetchQueryClient = new QueryClient({
446 defaultOptions: {
447 dehydrate: {
448 shouldDehydrateQuery: () => true,
449 },
450 },
451 })
452 void prefetchQueryClient
453 .query({
454 queryKey: ['promise'],
455 queryFn: () =>
456 sleep(10).then(() => Promise.reject(new Error('Query failed'))),
457 })
458 .catch(noop)
459​
460 const dehydratedState = dehydrate(prefetchQueryClient)
461​
462 // Mimic what React/our synchronous thenable does for already rejected promises
463 // @ts-expect-error
464 dehydratedState.queries[0].promise.status = 'failure'
465​
466 function Page() {
467 const { data } = useQuery({
468 queryKey: ['promise'],
469 queryFn: () => sleep(20).then(() => ['new']),
470 })
471 return (
472 <div>
473 <h1>{data}</h1>
474 </div>
475 )
476 }
477​
478 const rendered = render(
479 <QueryClientProvider client={clientQueryClient}>
480 <HydrationBoundary state={dehydratedState}>
481 <Page />
482 </HydrationBoundary>
483 </QueryClientProvider>,
484 )
485​
486 expect(rendered.getByText('existing')).toBeInTheDocument()
487 await vi.advanceTimersByTimeAsync(21)
488 expect(rendered.getByText('new')).toBeInTheDocument()
489​
490 prefetchQueryClient.clear()
491 clientQueryClient.clear()
492 })
493​
494 it('should not refetch when query has enabled set to false', async () => {
495 const queryFn = vi.fn<() => Promise<Array<string>>>()
496 const queryClient = new QueryClient()
497​
498 function Page() {
499 const { data } = useQuery({
500 queryKey: ['string'],
501 queryFn,
502 enabled: false,
503 })
504 return <div>{JSON.stringify(data)}</div>
505 }
506​
507 const rendered = render(
508 <QueryClientProvider client={queryClient}>
509 <HydrationBoundary state={JSON.parse(stringifiedState)}>
510 <Page />
511 </HydrationBoundary>
512 </QueryClientProvider>,
513 )
514​
515 expect(rendered.getByText('["stringCached"]')).toBeInTheDocument()
516 await vi.advanceTimersByTimeAsync(11)
517 expect(queryFn).toHaveBeenCalledTimes(0)
518 expect(rendered.getByText('["stringCached"]')).toBeInTheDocument()
519​
520 queryClient.clear()
521 })
522​
523 it('should not refetch when query has staleTime set to Infinity', async () => {
524 const queryFn = vi.fn<() => Promise<Array<string>>>()
525 const queryClient = new QueryClient()
526​
527 function Page() {
528 const { data } = useQuery({
529 queryKey: ['string'],
530 queryFn,
531 staleTime: Infinity,
532 })
533 return <div>{JSON.stringify(data)}</div>
534 }
535​
536 const rendered = render(
537 <QueryClientProvider client={queryClient}>
538 <HydrationBoundary state={JSON.parse(stringifiedState)}>
539 <Page />
540 </HydrationBoundary>
541 </QueryClientProvider>,
542 )
543​
544 expect(rendered.getByText('["stringCached"]')).toBeInTheDocument()
545 await vi.advanceTimersByTimeAsync(11)
546 expect(queryFn).toHaveBeenCalledTimes(0)
547 expect(rendered.getByText('["stringCached"]')).toBeInTheDocument()
548​
549 queryClient.clear()
550 })
551})