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

HydrationBoundary.test.tsx

365 lines10.7 KB

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