Open History to see the last commit
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
15}
16β
17async function fetchDate(value: string, ms?: number): Promise<Date> {
18 await sleep(ms || 0)
19 return new Date(value)
20}
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),
1006 )
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),
1042 )
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 }),
1060 )
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 }),
1077 )
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'),
1086 )
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'),
1124 )
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 },
1151 }
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),
1172 )
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),
1194 )
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'),
1299 )
1300 await promise
1301β
1302 process.env.NODE_ENV = originalNodeEnv
1303 consoleMock.mockRestore()
1304 })
1305})