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

hydration.test.tsx

1,305 lines36.2 KB

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