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

hydration.test.tsx

1,403 lines39.5 KB

1import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
2import { sleep } from '@tanstack/query-test-utils'
3import { QueryClient } from '../queryClient'
4import { QueryCache } from '../queryCache'
5import { dehydrate, hydrate } from '../hydration'
6import { MutationCache } from '../mutationCache'
7import { executeMutation, mockOnlineManagerIsOnline } from './utils'
8​
9describe('dehydration and rehydration', () => {
10 beforeEach(() => {
11 vi.useFakeTimers()
12 })
13​
14 afterEach(() => {
15 vi.useRealTimers()
16 })
17​
18 test('should work with serializable values', async () => {
19 const queryCache = new QueryCache()
20 const queryClient = new QueryClient({ queryCache })
21 await vi.waitFor(() =>
22 queryClient.prefetchQuery({
23 queryKey: ['string'],
24 queryFn: () => sleep(0).then(() => 'string'),
25 }),
26 )
27 await vi.waitFor(() =>
28 queryClient.prefetchQuery({
29 queryKey: ['number'],
30 queryFn: () => sleep(0).then(() => 1),
31 }),
32 )
33​
34 await vi.waitFor(() =>
35 queryClient.prefetchQuery({
36 queryKey: ['boolean'],
37 queryFn: () => sleep(0).then(() => true),
38 }),
39 )
40 await vi.waitFor(() =>
41 queryClient.prefetchQuery({
42 queryKey: ['null'],
43 queryFn: () => sleep(0).then(() => null),
44 }),
45 )
46 await vi.waitFor(() =>
47 queryClient.prefetchQuery({
48 queryKey: ['array'],
49 queryFn: () => sleep(0).then(() => ['string', 0]),
50 }),
51 )
52 await vi.waitFor(() =>
53 queryClient.prefetchQuery({
54 queryKey: ['nested'],
55 queryFn: () => sleep(0).then(() => ({ key: [{ nestedKey: 1 }] })),
56 }),
57 )
58 const dehydrated = dehydrate(queryClient)
59 const stringified = JSON.stringify(dehydrated)
60​
61 // ---
62​
63 const parsed = JSON.parse(stringified)
64 const hydrationCache = new QueryCache()
65 const hydrationClient = new QueryClient({
66 queryCache: hydrationCache,
67 })
68 hydrate(hydrationClient, parsed)
69 expect(hydrationCache.find({ queryKey: ['string'] })?.state.data).toBe(
70 'string',
71 )
72 expect(hydrationCache.find({ queryKey: ['number'] })?.state.data).toBe(1)
73 expect(hydrationCache.find({ queryKey: ['boolean'] })?.state.data).toBe(
74 true,
75 )
76 expect(hydrationCache.find({ queryKey: ['null'] })?.state.data).toBe(null)
77 expect(hydrationCache.find({ queryKey: ['array'] })?.state.data).toEqual([
78 'string',
79 0,
80 ])
81 expect(hydrationCache.find({ queryKey: ['nested'] })?.state.data).toEqual({
82 key: [{ nestedKey: 1 }],
83 })
84​
85 const fetchDataAfterHydration =
86 vi.fn<(...args: Array<unknown>) => unknown>()
87 await hydrationClient.prefetchQuery({
88 queryKey: ['string'],
89 queryFn: fetchDataAfterHydration,
90 staleTime: 1000,
91 })
92 await hydrationClient.prefetchQuery({
93 queryKey: ['number'],
94 queryFn: fetchDataAfterHydration,
95 staleTime: 1000,
96 })
97 await hydrationClient.prefetchQuery({
98 queryKey: ['boolean'],
99 queryFn: fetchDataAfterHydration,
100 staleTime: 1000,
101 })
102 await hydrationClient.prefetchQuery({
103 queryKey: ['null'],
104 queryFn: fetchDataAfterHydration,
105 staleTime: 1000,
106 })
107 await hydrationClient.prefetchQuery({
108 queryKey: ['array'],
109 queryFn: fetchDataAfterHydration,
110 staleTime: 1000,
111 })
112 await hydrationClient.prefetchQuery({
113 queryKey: ['nested'],
114 queryFn: fetchDataAfterHydration,
115 staleTime: 1000,
116 })
117 expect(fetchDataAfterHydration).toHaveBeenCalledTimes(0)
118​
119 queryClient.clear()
120 hydrationClient.clear()
121 })
122​
123 test('should not dehydrate queries if dehydrateQueries is set to false', () => {
124 const queryCache = new QueryCache()
125 const queryClient = new QueryClient({ queryCache })
126 vi.waitFor(() =>
127 queryClient.prefetchQuery({
128 queryKey: ['string'],
129 queryFn: () => sleep(0).then(() => 'string'),
130 }),
131 )
132​
133 const dehydrated = dehydrate(queryClient, {
134 shouldDehydrateQuery: () => false,
135 })
136​
137 expect(dehydrated.queries.length).toBe(0)
138​
139 queryClient.clear()
140 })
141​
142 test('should use the garbage collection time from the client', async () => {
143 const queryCache = new QueryCache()
144 const queryClient = new QueryClient({ queryCache })
145 await vi.waitFor(() =>
146 queryClient.prefetchQuery({
147 queryKey: ['string'],
148 queryFn: () => sleep(0).then(() => 'string'),
149 gcTime: 50,
150 }),
151 )
152 const dehydrated = dehydrate(queryClient)
153 const stringified = JSON.stringify(dehydrated)
154​
155 await vi.advanceTimersByTimeAsync(20)
156​
157 // ---
158​
159 const parsed = JSON.parse(stringified)
160 const hydrationCache = new QueryCache()
161 const hydrationClient = new QueryClient({ queryCache: hydrationCache })
162 hydrate(hydrationClient, parsed)
163 expect(hydrationCache.find({ queryKey: ['string'] })?.state.data).toBe(
164 'string',
165 )
166 await vi.advanceTimersByTimeAsync(100)
167 expect(hydrationCache.find({ queryKey: ['string'] })).toBeTruthy()
168​
169 queryClient.clear()
170 hydrationClient.clear()
171 })
172​
173 test('should be able to provide default options for the hydrated queries', async () => {
174 const queryCache = new QueryCache()
175 const queryClient = new QueryClient({ queryCache })
176 await vi.waitFor(() =>
177 queryClient.prefetchQuery({
178 queryKey: ['string'],
179 queryFn: () => sleep(0).then(() => 'string'),
180 }),
181 )
182 const dehydrated = dehydrate(queryClient)
183 const stringified = JSON.stringify(dehydrated)
184 const parsed = JSON.parse(stringified)
185 const hydrationCache = new QueryCache()
186 const hydrationClient = new QueryClient({ queryCache: hydrationCache })
187 hydrate(hydrationClient, parsed, {
188 defaultOptions: { queries: { retry: 10 } },
189 })
190 expect(hydrationCache.find({ queryKey: ['string'] })?.options.retry).toBe(
191 10,
192 )
193 queryClient.clear()
194 hydrationClient.clear()
195 })
196​
197 test('should respect query defaultOptions specified on the QueryClient', async () => {
198 const queryCache = new QueryCache()
199 const queryClient = new QueryClient({
200 queryCache,
201 defaultOptions: {
202 dehydrate: { shouldDehydrateQuery: () => true },
203 },
204 })
205 await vi.waitFor(() =>
206 queryClient.prefetchQuery({
207 queryKey: ['string'],
208 retry: 0,
209 queryFn: () => Promise.reject(new Error('error')),
210 }),
211 )
212 const dehydrated = dehydrate(queryClient)
213 expect(dehydrated.queries.length).toBe(1)
214 expect(dehydrated.queries[0]?.state.error).toStrictEqual(new Error('error'))
215 const stringified = JSON.stringify(dehydrated)
216 const parsed = JSON.parse(stringified)
217 const hydrationCache = new QueryCache()
218 const hydrationClient = new QueryClient({
219 queryCache: hydrationCache,
220 defaultOptions: { hydrate: { queries: { retry: 10 } } },
221 })
222 hydrate(hydrationClient, parsed, {
223 defaultOptions: { queries: { gcTime: 10 } },
224 })
225 expect(hydrationCache.find({ queryKey: ['string'] })?.options.retry).toBe(
226 10,
227 )
228 expect(hydrationCache.find({ queryKey: ['string'] })?.options.gcTime).toBe(
229 10,
230 )
231 queryClient.clear()
232 hydrationClient.clear()
233 })
234​
235 test('should respect mutation defaultOptions specified on the QueryClient', async () => {
236 const mutationCache = new MutationCache()
237 const queryClient = new QueryClient({
238 mutationCache,
239 defaultOptions: {
240 dehydrate: {
241 shouldDehydrateMutation: (mutation) => mutation.state.data === 'done',
242 },
243 },
244 })
245 await executeMutation(
246 queryClient,
247 {
248 mutationKey: ['string'],
249 mutationFn: () => Promise.resolve('done'),
250 },
251 undefined,
252 )
253​
254 const dehydrated = dehydrate(queryClient)
255 expect(dehydrated.mutations.length).toBe(1)
256 expect(dehydrated.mutations[0]?.state.data).toBe('done')
257 const stringified = JSON.stringify(dehydrated)
258 const parsed = JSON.parse(stringified)
259 const hydrationCache = new MutationCache()
260 const hydrationClient = new QueryClient({
261 mutationCache: hydrationCache,
262 defaultOptions: { hydrate: { mutations: { retry: 10 } } },
263 })
264 hydrate(hydrationClient, parsed, {
265 defaultOptions: { mutations: { gcTime: 10 } },
266 })
267 expect(
268 hydrationCache.find({ mutationKey: ['string'] })?.options.retry,
269 ).toBe(10)
270 expect(
271 hydrationCache.find({ mutationKey: ['string'] })?.options.gcTime,
272 ).toBe(10)
273 queryClient.clear()
274 hydrationClient.clear()
275 })
276​
277 test('should work with complex keys', async () => {
278 const queryCache = new QueryCache()
279 const queryClient = new QueryClient({ queryCache })
280 await vi.waitFor(() =>
281 queryClient.prefetchQuery({
282 queryKey: ['string', { key: ['string'], key2: 0 }],
283 queryFn: () => sleep(0).then(() => 'string'),
284 }),
285 )
286 const dehydrated = dehydrate(queryClient)
287 const stringified = JSON.stringify(dehydrated)
288​
289 // ---
290​
291 const parsed = JSON.parse(stringified)
292 const hydrationCache = new QueryCache()
293 const hydrationClient = new QueryClient({ queryCache: hydrationCache })
294 hydrate(hydrationClient, parsed)
295 expect(
296 hydrationCache.find({
297 queryKey: ['string', { key: ['string'], key2: 0 }],
298 })?.state.data,
299 ).toBe('string')
300​
301 const fetchDataAfterHydration =
302 vi.fn<(...args: Array<unknown>) => unknown>()
303 await vi.waitFor(() =>
304 hydrationClient.prefetchQuery({
305 queryKey: ['string', { key: ['string'], key2: 0 }],
306 queryFn: fetchDataAfterHydration,
307 staleTime: 100,
308 }),
309 )
310 expect(fetchDataAfterHydration).toHaveBeenCalledTimes(0)
311​
312 queryClient.clear()
313 hydrationClient.clear()
314 })
315​
316 test('should only hydrate successful queries by default', async () => {
317 const consoleMock = vi.spyOn(console, 'error')
318 consoleMock.mockImplementation(() => undefined)
319​
320 const queryCache = new QueryCache()
321 const queryClient = new QueryClient({ queryCache })
322 await vi.waitFor(() =>
323 queryClient.prefetchQuery({
324 queryKey: ['success'],
325 queryFn: () => sleep(0).then(() => 'success'),
326 }),
327 )
328 queryClient.prefetchQuery({
329 queryKey: ['loading'],
330 queryFn: () => sleep(10000).then(() => 'loading'),
331 })
332 await vi.waitFor(() =>
333 queryClient.prefetchQuery({
334 queryKey: ['error'],
335 queryFn: () => {
336 throw new Error()
337 },
338 }),
339 )
340 const dehydrated = dehydrate(queryClient)
341 const stringified = JSON.stringify(dehydrated)
342​
343 // ---
344​
345 const parsed = JSON.parse(stringified)
346 const hydrationCache = new QueryCache()
347 const hydrationClient = new QueryClient({ queryCache: hydrationCache })
348 hydrate(hydrationClient, parsed)
349​
350 expect(hydrationCache.find({ queryKey: ['success'] })).toBeTruthy()
351 expect(hydrationCache.find({ queryKey: ['loading'] })).toBeFalsy()
352 expect(hydrationCache.find({ queryKey: ['error'] })).toBeFalsy()
353​
354 queryClient.clear()
355 hydrationClient.clear()
356 consoleMock.mockRestore()
357 })
358​
359 test('should filter queries via dehydrateQuery', async () => {
360 const queryCache = new QueryCache()
361 const queryClient = new QueryClient({ queryCache })
362 await vi.waitFor(() =>
363 queryClient.prefetchQuery({
364 queryKey: ['string'],
365 queryFn: () => sleep(0).then(() => 'string'),
366 }),
367 )
368 await vi.waitFor(() =>
369 queryClient.prefetchQuery({
370 queryKey: ['number'],
371 queryFn: () => sleep(0).then(() => 1),
372 }),
373 )
374 const dehydrated = dehydrate(queryClient, {
375 shouldDehydrateQuery: (query) => query.queryKey[0] !== 'string',
376 })
377​
378 // This is testing implementation details that can change and are not
379 // part of the public API, but is important for keeping the payload small
380 const dehydratedQuery = dehydrated.queries.find(
381 (query) => query.queryKey[0] === 'string',
382 )
383 expect(dehydratedQuery).toBeUndefined()
384​
385 const stringified = JSON.stringify(dehydrated)
386​
387 // ---
388​
389 const parsed = JSON.parse(stringified)
390 const hydrationCache = new QueryCache()
391 const hydrationClient = new QueryClient({ queryCache: hydrationCache })
392 hydrate(hydrationClient, parsed)
393 expect(hydrationCache.find({ queryKey: ['string'] })).toBeUndefined()
394 expect(hydrationCache.find({ queryKey: ['number'] })?.state.data).toBe(1)
395​
396 queryClient.clear()
397 hydrationClient.clear()
398 })
399​
400 test('should not overwrite query in cache if hydrated query is older', async () => {
401 const queryCache = new QueryCache()
402 const queryClient = new QueryClient({ queryCache })
403 await vi.waitFor(() =>
404 queryClient.prefetchQuery({
405 queryKey: ['string'],
406 queryFn: () => sleep(5).then(() => 'string-older'),
407 }),
408 )
409 const dehydrated = dehydrate(queryClient)
410 const stringified = JSON.stringify(dehydrated)
411​
412 // ---
413​
414 const parsed = JSON.parse(stringified)
415 const hydrationCache = new QueryCache()
416 const hydrationClient = new QueryClient({ queryCache: hydrationCache })
417 await vi.waitFor(() =>
418 hydrationClient.prefetchQuery({
419 queryKey: ['string'],
420 queryFn: () => sleep(5).then(() => 'string-newer'),
421 }),
422 )
423​
424 hydrate(hydrationClient, parsed)
425 expect(hydrationCache.find({ queryKey: ['string'] })?.state.data).toBe(
426 'string-newer',
427 )
428​
429 queryClient.clear()
430 hydrationClient.clear()
431 })
432​
433 test('should overwrite query in cache if hydrated query is newer', async () => {
434 const hydrationCache = new QueryCache()
435 const hydrationClient = new QueryClient({ queryCache: hydrationCache })
436 await vi.waitFor(() =>
437 hydrationClient.prefetchQuery({
438 queryKey: ['string'],
439 queryFn: () => sleep(5).then(() => 'string-older'),
440 }),
441 )
442​
443 // ---
444​
445 const queryCache = new QueryCache()
446 const queryClient = new QueryClient({ queryCache })
447 await vi.waitFor(() =>
448 queryClient.prefetchQuery({
449 queryKey: ['string'],
450 queryFn: () => sleep(5).then(() => 'string-newer'),
451 }),
452 )
453 const dehydrated = dehydrate(queryClient)
454 const stringified = JSON.stringify(dehydrated)
455​
456 // ---
457​
458 const parsed = JSON.parse(stringified)
459 hydrate(hydrationClient, parsed)
460 expect(hydrationCache.find({ queryKey: ['string'] })?.state.data).toBe(
461 'string-newer',
462 )
463​
464 queryClient.clear()
465 hydrationClient.clear()
466 })
467​
468 test('should be able to dehydrate mutations and continue on hydration', async () => {
469 const consoleMock = vi.spyOn(console, 'error')
470 consoleMock.mockImplementation(() => undefined)
471 const onlineMock = mockOnlineManagerIsOnline(false)
472​
473 const serverAddTodo = vi
474 .fn()
475 .mockImplementation(() => Promise.reject(new Error('offline')))
476 const serverOnMutate = vi
477 .fn()
478 .mockImplementation((variables: { text: string }) => {
479 const optimisticTodo = { id: 1, text: variables.text }
480 return { optimisticTodo }
481 })
482 const serverOnSuccess = vi.fn()
483​
484 const serverClient = new QueryClient()
485​
486 serverClient.setMutationDefaults(['addTodo'], {
487 mutationFn: serverAddTodo,
488 onMutate: serverOnMutate,
489 onSuccess: serverOnSuccess,
490 retry: 3,
491 retryDelay: 10,
492 })
493​
494 executeMutation(
495 serverClient,
496 {
497 mutationKey: ['addTodo'],
498 },
499 { text: 'text' },
500 ).catch(() => undefined)
501​
502 await vi.advanceTimersByTimeAsync(50)
503​
504 const dehydrated = dehydrate(serverClient)
505 const stringified = JSON.stringify(dehydrated)
506​
507 serverClient.clear()
508​
509 // ---
510​
511 onlineMock.mockReturnValue(true)
512​
513 const parsed = JSON.parse(stringified)
514 const client = new QueryClient()
515​
516 const clientAddTodo = vi
517 .fn()
518 .mockImplementation((variables: { text: string }) => {
519 return { id: 2, text: variables.text }
520 })
521 const clientOnMutate = vi
522 .fn()
523 .mockImplementation((variables: { text: string }) => {
524 const optimisticTodo = { id: 1, text: variables.text }
525 return { optimisticTodo }
526 })
527 const clientOnSuccess = vi.fn()
528​
529 client.setMutationDefaults(['addTodo'], {
530 mutationFn: clientAddTodo,
531 onMutate: clientOnMutate,
532 onSuccess: clientOnSuccess,
533 retry: 3,
534 retryDelay: 10,
535 })
536​
537 hydrate(client, parsed)
538​
539 await client.resumePausedMutations()
540​
541 expect(clientAddTodo).toHaveBeenCalledTimes(1)
542 expect(clientOnMutate).not.toHaveBeenCalled()
543 expect(clientOnSuccess).toHaveBeenCalledTimes(1)
544 expect(clientOnSuccess).toHaveBeenCalledWith(
545 { id: 2, text: 'text' },
546 { text: 'text' },
547 { optimisticTodo: { id: 1, text: 'text' } },
548 { client: client, meta: undefined, mutationKey: ['addTodo'] },
549 )
550​
551 client.clear()
552 consoleMock.mockRestore()
553 onlineMock.mockRestore()
554 })
555​
556 test('should not dehydrate mutations if dehydrateMutations is set to false', async () => {
557 const consoleMock = vi.spyOn(console, 'error')
558 consoleMock.mockImplementation(() => undefined)
559​
560 const serverAddTodo = vi
561 .fn()
562 .mockImplementation(() => Promise.reject(new Error('offline')))
563​
564 const queryClient = new QueryClient()
565​
566 queryClient.setMutationDefaults(['addTodo'], {
567 mutationFn: serverAddTodo,
568 retry: false,
569 })
570​
571 executeMutation(
572 queryClient,
573 {
574 mutationKey: ['addTodo'],
575 },
576 { text: 'text' },
577 ).catch(() => undefined)
578​
579 await vi.advanceTimersByTimeAsync(1)
580 const dehydrated = dehydrate(queryClient, {
581 shouldDehydrateMutation: () => false,
582 })
583​
584 expect(dehydrated.mutations.length).toBe(0)
585​
586 queryClient.clear()
587 consoleMock.mockRestore()
588 })
589​
590 test('should not dehydrate mutation if mutation state is set to pause', async () => {
591 const consoleMock = vi.spyOn(console, 'error')
592 consoleMock.mockImplementation(() => undefined)
593​
594 const serverAddTodo = vi
595 .fn()
596 .mockImplementation(() => Promise.reject(new Error('offline')))
597​
598 const queryClient = new QueryClient()
599​
600 queryClient.setMutationDefaults(['addTodo'], {
601 mutationFn: serverAddTodo,
602 retry: 1,
603 retryDelay: 20,
604 })
605​
606 executeMutation(
607 queryClient,
608 {
609 mutationKey: ['addTodo'],
610 },
611 { text: 'text' },
612 ).catch(() => undefined)
613​
614 // Dehydrate mutation between retries
615 await vi.advanceTimersByTimeAsync(1)
616 const dehydrated = dehydrate(queryClient)
617​
618 expect(dehydrated.mutations.length).toBe(0)
619​
620 await vi.advanceTimersByTimeAsync(30)
621 queryClient.clear()
622 consoleMock.mockRestore()
623 })
624​
625 test('should not hydrate if the hydratedState is null or is not an object', () => {
626 const queryCache = new QueryCache()
627 const queryClient = new QueryClient({ queryCache })
628​
629 expect(() => hydrate(queryClient, null)).not.toThrow()
630 expect(() => hydrate(queryClient, 'invalid')).not.toThrow()
631​
632 queryClient.clear()
633 })
634​
635 test('should support hydratedState with undefined queries and mutations', () => {
636 const queryCache = new QueryCache()
637 const queryClient = new QueryClient({ queryCache })
638​
639 expect(() => hydrate(queryClient, {})).not.toThrow()
640 expect(() => hydrate(queryClient, {})).not.toThrow()
641​
642 queryClient.clear()
643 })
644​
645 test('should set the fetchStatus to idle when creating a query with dehydrate', async () => {
646 const queryCache = new QueryCache()
647 const queryClient = new QueryClient({ queryCache })
648​
649 let isInitialFetch = true
650 let resolvePromise: (value: unknown) => void = () => undefined
651​
652 const customFetchData = () => {
653 const promise = new Promise((resolve) => {
654 resolvePromise = resolve
655 })
656 // Resolve the promise in initial fetch
657 // because we are awaiting the query first time
658 if (isInitialFetch) {
659 resolvePromise('string')
660 }
661 isInitialFetch = false
662 return promise
663 }
664​
665 await queryClient.prefetchQuery({
666 queryKey: ['string'],
667 queryFn: () => customFetchData(),
668 })
669​
670 queryClient.refetchQueries({ queryKey: ['string'] })
671​
672 const dehydrated = dehydrate(queryClient)
673 resolvePromise('string')
674 expect(
675 dehydrated.queries.find((q) => q.queryHash === '["string"]')?.state
676 .fetchStatus,
677 ).toBe('fetching')
678 const stringified = JSON.stringify(dehydrated)
679​
680 // ---
681 const parsed = JSON.parse(stringified)
682 const hydrationCache = new QueryCache()
683 const hydrationClient = new QueryClient({ queryCache: hydrationCache })
684 hydrate(hydrationClient, parsed)
685 expect(
686 hydrationCache.find({ queryKey: ['string'] })?.state.fetchStatus,
687 ).toBe('idle')
688 })
689​
690 test('should dehydrate and hydrate meta for queries', async () => {
691 const queryCache = new QueryCache()
692 const queryClient = new QueryClient({ queryCache })
693 await vi.waitFor(() =>
694 queryClient.prefetchQuery({
695 queryKey: ['meta'],
696 queryFn: () => Promise.resolve('meta'),
697 meta: {
698 some: 'meta',
699 },
700 }),
701 )
702 await vi.waitFor(() =>
703 queryClient.prefetchQuery({
704 queryKey: ['no-meta'],
705 queryFn: () => Promise.resolve('no-meta'),
706 }),
707 )
708​
709 const dehydrated = dehydrate(queryClient)
710​
711 expect(
712 dehydrated.queries.find((q) => q.queryHash === '["meta"]')?.meta,
713 ).toEqual({
714 some: 'meta',
715 })
716​
717 expect(
718 dehydrated.queries.find((q) => q.queryHash === '["no-meta"]')?.meta,
719 ).toEqual(undefined)
720​
721 expect(
722 Object.keys(
723 dehydrated.queries.find((q) => q.queryHash === '["no-meta"]')!,
724 ),
725 ).not.toEqual(expect.arrayContaining(['meta']))
726​
727 const stringified = JSON.stringify(dehydrated)
728​
729 // ---
730​
731 const parsed = JSON.parse(stringified)
732 const hydrationCache = new QueryCache()
733 const hydrationClient = new QueryClient({
734 queryCache: hydrationCache,
735 })
736 hydrate(hydrationClient, parsed)
737 expect(hydrationCache.find({ queryKey: ['meta'] })?.meta).toEqual({
738 some: 'meta',
739 })
740 expect(hydrationCache.find({ queryKey: ['no-meta'] })?.meta).toEqual(
741 undefined,
742 )
743 })
744​
745 test('should dehydrate and hydrate meta for mutations', async () => {
746 const mutationCache = new MutationCache()
747 const queryClient = new QueryClient({ mutationCache })
748​
749 await executeMutation(
750 queryClient,
751 {
752 mutationKey: ['meta'],
753 mutationFn: () => Promise.resolve('meta'),
754 meta: {
755 some: 'meta',
756 },
757 },
758 undefined,
759 )
760​
761 await executeMutation(
762 queryClient,
763 {
764 mutationKey: ['no-meta'],
765 mutationFn: () => Promise.resolve('no-meta'),
766 },
767 undefined,
768 )
769​
770 const dehydrated = dehydrate(queryClient, {
771 shouldDehydrateMutation: () => true,
772 })
773​
774 expect(Object.keys(dehydrated.mutations[0]!)).toEqual(
775 expect.arrayContaining(['meta']),
776 )
777 expect(dehydrated.mutations[0]?.meta).toEqual({
778 some: 'meta',
779 })
780​
781 expect(Object.keys(dehydrated.mutations[1]!)).not.toEqual(
782 expect.arrayContaining(['meta']),
783 )
784 expect(dehydrated.mutations[1]?.meta).toEqual(undefined)
785​
786 const stringified = JSON.stringify(dehydrated)
787​
788 // ---
789​
790 const parsed = JSON.parse(stringified)
791 const hydrationCache = new MutationCache()
792 const hydrationClient = new QueryClient({
793 mutationCache: hydrationCache,
794 })
795 hydrate(hydrationClient, parsed)
796 expect(hydrationCache.find({ mutationKey: ['meta'] })?.meta).toEqual({
797 some: 'meta',
798 })
799 expect(hydrationCache.find({ mutationKey: ['no-meta'] })?.meta).toEqual(
800 undefined,
801 )
802 })
803​
804 test('should not change fetchStatus when updating a query with dehydrate', async () => {
805 const queryClient = new QueryClient()
806​
807 const options = {
808 queryKey: ['string'],
809 queryFn: async () => {
810 await sleep(10)
811 return 'string'
812 },
813 } as const
814​
815 await vi.waitFor(() => queryClient.prefetchQuery(options))
816​
817 const dehydrated = dehydrate(queryClient)
818 expect(
819 dehydrated.queries.find((q) => q.queryHash === '["string"]')?.state
820 .fetchStatus,
821 ).toBe('idle')
822 const stringified = JSON.stringify(dehydrated)
823​
824 // ---
825 const parsed = JSON.parse(stringified)
826 const hydrationCache = new QueryCache()
827 const hydrationClient = new QueryClient({ queryCache: hydrationCache })
828​
829 const promise = hydrationClient.prefetchQuery(options)
830 hydrate(hydrationClient, parsed)
831 expect(
832 hydrationCache.find({ queryKey: ['string'] })?.state.fetchStatus,
833 ).toBe('fetching')
834 await vi.waitFor(() => promise)
835 expect(
836 hydrationCache.find({ queryKey: ['string'] })?.state.fetchStatus,
837 ).toBe('idle')
838 })
839​
840 test('should dehydrate and hydrate mutation scopes', () => {
841 const queryClient = new QueryClient()
842 const onlineMock = mockOnlineManagerIsOnline(false)
843​
844 void executeMutation(
845 queryClient,
846 {
847 mutationKey: ['mutation'],
848 mutationFn: () => {
849 return Promise.resolve('mutation')
850 },
851 scope: {
852 id: 'scope',
853 },
854 },
855 'vars',
856 )
857​
858 const dehydrated = dehydrate(queryClient)
859 expect(dehydrated.mutations[0]?.scope?.id).toBe('scope')
860 const stringified = JSON.stringify(dehydrated)
861​
862 // ---
863 const parsed = JSON.parse(stringified)
864 const hydrationCache = new MutationCache()
865 const hydrationClient = new QueryClient({ mutationCache: hydrationCache })
866​
867 hydrate(hydrationClient, parsed)
868​
869 expect(dehydrated.mutations[0]?.scope?.id).toBe('scope')
870​
871 onlineMock.mockRestore()
872 })
873​
874 test('should dehydrate promises for pending queries', async () => {
875 const queryCache = new QueryCache()
876 const queryClient = new QueryClient({
877 queryCache,
878 defaultOptions: { dehydrate: { shouldDehydrateQuery: () => true } },
879 })
880 await vi.waitFor(() =>
881 queryClient.prefetchQuery({
882 queryKey: ['success'],
883 queryFn: () => sleep(0).then(() => 'success'),
884 }),
885 )
886​
887 const promise = queryClient.prefetchQuery({
888 queryKey: ['pending'],
889 queryFn: () => sleep(10).then(() => 'pending'),
890 })
891 const dehydrated = dehydrate(queryClient)
892​
893 expect(dehydrated.queries[0]?.promise).toBeUndefined()
894 expect(dehydrated.queries[1]?.promise).toBeInstanceOf(Promise)
895​
896 await vi.waitFor(() => promise)
897 queryClient.clear()
898 })
899​
900 test('should hydrate promises even without observers', async () => {
901 const queryCache = new QueryCache()
902 const queryClient = new QueryClient({
903 queryCache,
904 defaultOptions: { dehydrate: { shouldDehydrateQuery: () => true } },
905 })
906 await vi.waitFor(() =>
907 queryClient.prefetchQuery({
908 queryKey: ['success'],
909 queryFn: () => sleep(0).then(() => 'success'),
910 }),
911 )
912​
913 void queryClient.prefetchQuery({
914 queryKey: ['pending'],
915 queryFn: () => sleep(20).then(() => 'pending'),
916 })
917 const dehydrated = dehydrate(queryClient)
918 // no stringify/parse here because promises can't be serialized to json
919 // but nextJs still can do it
920​
921 const hydrationCache = new QueryCache()
922 const hydrationClient = new QueryClient({
923 queryCache: hydrationCache,
924 })
925​
926 hydrate(hydrationClient, dehydrated)
927​
928 expect(hydrationCache.find({ queryKey: ['success'] })?.state.data).toBe(
929 'success',
930 )
931​
932 expect(hydrationCache.find({ queryKey: ['pending'] })?.state).toMatchObject(
933 {
934 data: undefined,
935 dataUpdateCount: 0,
936 dataUpdatedAt: 0,
937 error: null,
938 errorUpdateCount: 0,
939 errorUpdatedAt: 0,
940 fetchFailureCount: 0,
941 fetchFailureReason: null,
942 fetchMeta: null,
943 fetchStatus: 'fetching',
944 isInvalidated: false,
945 status: 'pending',
946 },
947 )
948​
949 await vi.waitFor(() =>
950 expect(
951 hydrationCache.find({ queryKey: ['pending'] })?.state,
952 ).toMatchObject({
953 data: 'pending',
954 dataUpdateCount: 1,
955 dataUpdatedAt: expect.any(Number),
956 error: null,
957 errorUpdateCount: 0,
958 errorUpdatedAt: 0,
959 fetchFailureCount: 0,
960 fetchFailureReason: null,
961 fetchMeta: null,
962 fetchStatus: 'idle',
963 isInvalidated: false,
964 status: 'success',
965 }),
966 )
967 })
968​
969 test('should transform promise result', async () => {
970 const queryClient = new QueryClient({
971 defaultOptions: {
972 dehydrate: {
973 shouldDehydrateQuery: () => true,
974 serializeData: (data) => data.toISOString(),
975 },
976 },
977 })
978​
979 const promise = queryClient.prefetchQuery({
980 queryKey: ['transformedStringToDate'],
981 queryFn: () => sleep(20).then(() => new Date('2024-01-01T00:00:00.000Z')),
982 })
983 const dehydrated = dehydrate(queryClient)
984 expect(dehydrated.queries[0]?.promise).toBeInstanceOf(Promise)
985​
986 const hydrationClient = new QueryClient({
987 defaultOptions: {
988 hydrate: {
989 deserializeData: (data) => new Date(data),
990 },
991 },
992 })
993​
994 hydrate(hydrationClient, dehydrated)
995 await vi.waitFor(() => promise)
996 await vi.waitFor(() =>
997 expect(
998 hydrationClient.getQueryData(['transformedStringToDate']),
999 ).toBeInstanceOf(Date),
1001​
1002 queryClient.clear()
1003 })
1004​
1005 test('should transform query data if promise is already resolved', async () => {
1006 const queryClient = new QueryClient({
1007 defaultOptions: {
1008 dehydrate: {
1009 shouldDehydrateQuery: () => true,
1010 serializeData: (data) => data.toISOString(),
1011 },
1012 },
1013 })
1014​
1015 const promise = queryClient.prefetchQuery({
1016 queryKey: ['transformedStringToDate'],
1017 queryFn: () => sleep(0).then(() => new Date('2024-01-01T00:00:00.000Z')),
1018 })
1019 await vi.advanceTimersByTimeAsync(20)
1020 const dehydrated = dehydrate(queryClient)
1021​
1022 const hydrationClient = new QueryClient({
1023 defaultOptions: {
1024 hydrate: {
1025 deserializeData: (data) => new Date(data),
1026 },
1027 },
1028 })
1029​
1030 hydrate(hydrationClient, dehydrated)
1031 await vi.waitFor(() => promise)
1032 await vi.waitFor(() =>
1033 expect(
1034 hydrationClient.getQueryData(['transformedStringToDate']),
1035 ).toBeInstanceOf(Date),
1037​
1038 queryClient.clear()
1039 })
1040​
1041 test('should overwrite query in cache if hydrated query is newer (with transformation)', async () => {
1042 const hydrationClient = new QueryClient({
1043 defaultOptions: {
1044 hydrate: {
1045 deserializeData: (data) => new Date(data),
1046 },
1047 },
1048 })
1049 await vi.waitFor(() =>
1050 hydrationClient.prefetchQuery({
1051 queryKey: ['date'],
1052 queryFn: () =>
1053 sleep(5).then(() => new Date('2024-01-01T00:00:00.000Z')),
1054 }),
1056​
1057 // ---
1058​
1059 const queryClient = new QueryClient({
1060 defaultOptions: {
1061 dehydrate: {
1062 shouldDehydrateQuery: () => true,
1063 serializeData: (data) => data.toISOString(),
1064 },
1065 },
1066 })
1067 await vi.waitFor(() =>
1068 queryClient.prefetchQuery({
1069 queryKey: ['date'],
1070 queryFn: () =>
1071 sleep(10).then(() => new Date('2024-01-02T00:00:00.000Z')),
1072 }),
1074 const dehydrated = dehydrate(queryClient)
1075​
1076 // ---
1077​
1078 hydrate(hydrationClient, dehydrated)
1079​
1080 expect(hydrationClient.getQueryData(['date'])).toStrictEqual(
1081 new Date('2024-01-02T00:00:00.000Z'),
1083​
1084 queryClient.clear()
1085 hydrationClient.clear()
1086 })
1087​
1088 test('should overwrite query in cache if hydrated query is newer (with promise)', async () => {
1089 // --- server ---
1090​
1091 const serverQueryClient = new QueryClient({
1092 defaultOptions: {
1093 dehydrate: {
1094 shouldDehydrateQuery: () => true,
1095 },
1096 },
1097 })
1098​
1099 const promise = serverQueryClient.prefetchQuery({
1100 queryKey: ['data'],
1101 queryFn: async () => {
1102 await sleep(10)
1103 return 'server data'
1104 },
1105 })
1106​
1107 const dehydrated = dehydrate(serverQueryClient)
1108​
1109 // --- client ---
1110​
1111 const clientQueryClient = new QueryClient()
1112​
1113 clientQueryClient.setQueryData(['data'], 'old data', { updatedAt: 10 })
1114​
1115 hydrate(clientQueryClient, dehydrated)
1116​
1117 await vi.waitFor(() => promise)
1118 await vi.waitFor(() =>
1119 expect(clientQueryClient.getQueryData(['data'])).toBe('server data'),
1121​
1122 clientQueryClient.clear()
1123 serverQueryClient.clear()
1124 })
1125​
1126 test('should not overwrite query in cache if existing query is newer (with promise)', async () => {
1127 // --- server ---
1128​
1129 const serverQueryClient = new QueryClient({
1130 defaultOptions: {
1131 dehydrate: {
1132 shouldDehydrateQuery: () => true,
1133 },
1134 },
1135 })
1136​
1137 const promise = serverQueryClient.prefetchQuery({
1138 queryKey: ['data'],
1139 queryFn: async () => {
1140 await sleep(10)
1141 return 'server data'
1142 },
1143 })
1144​
1145 const dehydrated = dehydrate(serverQueryClient)
1146​
1147 await vi.advanceTimersByTimeAsync(10)
1148 await promise
1149​
1150 // Pretend the output of this server part is cached for a long time
1151​
1152 // --- client ---
1153​
1154 await vi.advanceTimersByTimeAsync(10_000) // Arbitrary time in the future
1155​
1156 const clientQueryClient = new QueryClient()
1157​
1158 clientQueryClient.setQueryData(['data'], 'newer data', {
1159 updatedAt: Date.now(),
1160 })
1161​
1162 hydrate(clientQueryClient, dehydrated)
1163​
1164 // If the query was hydrated in error, it would still take some time for it
1165 // to end up in the cache, so for the test to fail properly on regressions,
1166 // wait for the fetchStatus to be idle
1167 await vi.waitFor(() =>
1168 expect(clientQueryClient.getQueryState(['data'])?.fetchStatus).toBe(
1169 'idle',
1170 ),
1172 await vi.waitFor(() =>
1173 expect(clientQueryClient.getQueryData(['data'])).toBe('newer data'),
1175​
1176 clientQueryClient.clear()
1177 serverQueryClient.clear()
1178 })
1179​
1180 test('should overwrite data when a new promise is streamed in', async () => {
1181 const serializeDataMock = vi.fn((data: any) => data)
1182 const deserializeDataMock = vi.fn((data: any) => data)
1183​
1184 const countRef = { current: 0 }
1185 // --- server ---
1186 const serverQueryClient = new QueryClient({
1187 defaultOptions: {
1188 dehydrate: {
1189 shouldDehydrateQuery: () => true,
1190 serializeData: serializeDataMock,
1191 },
1192 },
1193 })
1194​
1195 const query = {
1196 queryKey: ['data'],
1197 queryFn: async () => {
1198 await sleep(10)
1199 return countRef.current
1200 },
1202​
1203 const promise = serverQueryClient.prefetchQuery(query)
1204​
1205 let dehydrated = dehydrate(serverQueryClient)
1206​
1207 // --- client ---
1208​
1209 const clientQueryClient = new QueryClient({
1210 defaultOptions: {
1211 hydrate: {
1212 deserializeData: deserializeDataMock,
1213 },
1214 },
1215 })
1216​
1217 hydrate(clientQueryClient, dehydrated)
1218​
1219 await vi.waitFor(() => promise)
1220 await vi.waitFor(() =>
1221 expect(clientQueryClient.getQueryData(query.queryKey)).toBe(0),
1223​
1224 expect(serializeDataMock).toHaveBeenCalledTimes(1)
1225 expect(serializeDataMock).toHaveBeenCalledWith(0)
1226​
1227 expect(deserializeDataMock).toHaveBeenCalledTimes(1)
1228 expect(deserializeDataMock).toHaveBeenCalledWith(0)
1229​
1230 // --- server ---
1231 countRef.current++
1232 serverQueryClient.clear()
1233 const promise2 = serverQueryClient.prefetchQuery(query)
1234​
1235 dehydrated = dehydrate(serverQueryClient)
1236​
1237 // --- client ---
1238​
1239 hydrate(clientQueryClient, dehydrated)
1240​
1241 await vi.waitFor(() => promise2)
1242 await vi.waitFor(() =>
1243 expect(clientQueryClient.getQueryData(query.queryKey)).toBe(1),
1245​
1246 expect(serializeDataMock).toHaveBeenCalledTimes(2)
1247 expect(serializeDataMock).toHaveBeenCalledWith(1)
1248​
1249 expect(deserializeDataMock).toHaveBeenCalledTimes(2)
1250 expect(deserializeDataMock).toHaveBeenCalledWith(1)
1251​
1252 clientQueryClient.clear()
1253 serverQueryClient.clear()
1254 })
1255​
1256 test('should not redact errors when shouldRedactErrors returns false', async () => {
1257 const queryCache = new QueryCache()
1258 const queryClient = new QueryClient({
1259 queryCache,
1260 defaultOptions: {
1261 dehydrate: {
1262 shouldDehydrateQuery: () => true,
1263 shouldRedactErrors: () => false,
1264 },
1265 },
1266 })
1267​
1268 const testError = new Error('original error')
1269​
1270 const promise = queryClient
1271 .prefetchQuery({
1272 queryKey: ['error'],
1273 queryFn: () => Promise.reject(testError),
1274 retry: false,
1275 })
1276 .catch(() => undefined)
1277​
1278 const dehydrated = dehydrate(queryClient)
1279​
1280 expect(dehydrated.queries[0]?.promise).toBeInstanceOf(Promise)
1281 await expect(dehydrated.queries[0]?.promise).rejects.toBe(testError)
1282 await promise
1283 })
1284​
1285 test('should handle errors in promises for pending queries', async () => {
1286 const consoleMock = vi.spyOn(console, 'error')
1287 consoleMock.mockImplementation(() => undefined)
1288​
1289 const queryCache = new QueryCache()
1290 const queryClient = new QueryClient({
1291 queryCache,
1292 defaultOptions: {
1293 dehydrate: {
1294 shouldDehydrateQuery: () => true,
1295 },
1296 },
1297 })
1298​
1299 const promise = queryClient
1300 .prefetchQuery({
1301 queryKey: ['error'],
1302 queryFn: () => Promise.reject(new Error('test error')),
1303 retry: false,
1304 })
1305 .catch(() => undefined)
1306​
1307 const dehydrated = dehydrate(queryClient)
1308​
1309 expect(dehydrated.queries[0]?.promise).toBeInstanceOf(Promise)
1310​
1311 await expect(dehydrated.queries[0]?.promise).rejects.toThrow('redacted')
1312 await promise
1313 consoleMock.mockRestore()
1314 })
1315​
1316 test('should log error in development environment when redacting errors', async () => {
1317 const originalNodeEnv = process.env.NODE_ENV
1318 process.env.NODE_ENV = 'development'
1319​
1320 const consoleMock = vi.spyOn(console, 'error')
1321 consoleMock.mockImplementation(() => undefined)
1322​
1323 const queryCache = new QueryCache()
1324 const queryClient = new QueryClient({
1325 queryCache,
1326 defaultOptions: {
1327 dehydrate: {
1328 shouldDehydrateQuery: () => true,
1329 shouldRedactErrors: () => true,
1330 },
1331 },
1332 })
1333​
1334 const testError = new Error('test error')
1335​
1336 const promise = queryClient
1337 .prefetchQuery({
1338 queryKey: ['error'],
1339 queryFn: () => Promise.reject(testError),
1340 retry: false,
1341 })
1342 .catch(() => undefined)
1343​
1344 const dehydrated = dehydrate(queryClient)
1345​
1346 await expect(dehydrated.queries[0]?.promise).rejects.toThrow('redacted')
1347 expect(consoleMock).toHaveBeenCalledWith(
1348 expect.stringContaining('test error'),
1350 await promise
1351​
1352 process.env.NODE_ENV = originalNodeEnv
1353 consoleMock.mockRestore()
1354 })
1355​
1356 // When React hydrates promises across RSC/client boundaries, it passes
1357 // them as special ReactPromise types. There are situations where the
1358 // promise might have time to resolve before we end up hydrating it, in
1359 // which case React will have made it a special synchronous thenable where
1360 // .then() resolves immediately.
1361 // In these cases it's important we hydrate the data synchronously, or else
1362 // the data in the cache wont match the content that was rendered on the server.
1363 // What can end up happening otherwise is that the content is visible from the
1364 // server, but the client renders a Suspense fallback, only to immediately show
1365 // the data again.
1366 test('should rehydrate synchronous thenable immediately', async () => {
1367 // --- server ---
1368​
1369 const serverQueryClient = new QueryClient({
1370 defaultOptions: {
1371 dehydrate: {
1372 shouldDehydrateQuery: () => true,
1373 },
1374 },
1375 })
1376 const originalPromise = serverQueryClient.prefetchQuery({
1377 queryKey: ['data'],
1378 queryFn: () => null,
1379 })
1380​
1381 const dehydrated = dehydrate(serverQueryClient)
1382​
1383 // --- server end ---
1384​
1385 // Simulate a synchronous thenable
1386 // @ts-expect-error
1387 dehydrated.queries[0].promise.then = (cb) => {
1388 cb?.('server data')
1390​
1391 // --- client ---
1392​
1393 const clientQueryClient = new QueryClient()
1394 hydrate(clientQueryClient, dehydrated)
1395​
1396 // If data is already resolved, it should end up in the cache immediately
1397 expect(clientQueryClient.getQueryData(['data'])).toBe('server data')
1398​
1399 // Need to await the original promise or else it will get a cancellation
1400 // error and test will fail
1401 await originalPromise
1402 })