Open History to see the last commit
1import { 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β
17describe('dehydration and rehydration', () => {
18 test('should work with serializable values', async () => {
19 const queryCache = new QueryCache()
20 const queryClient = createQueryClient({ queryCache })
21 await queryClient.prefetchQuery({
22 queryKey: ['string'],
23 queryFn: () => fetchData('string'),
24 })
25 await queryClient.prefetchQuery({
26 queryKey: ['number'],
27 queryFn: () => fetchData(1),
28 })
29 await queryClient.prefetchQuery({
30 queryKey: ['boolean'],
31 queryFn: () => fetchData(true),
32 })
33 await queryClient.prefetchQuery({
34 queryKey: ['null'],
35 queryFn: () => fetchData(null),
36 })
37 await queryClient.prefetchQuery({
38 queryKey: ['array'],
39 queryFn: () => fetchData(['string', 0]),
40 })
41 await queryClient.prefetchQuery({
42 queryKey: ['nested'],
43 queryFn: () => fetchData({ key: [{ nestedKey: 1 }] }),
44 })
45 const dehydrated = dehydrate(queryClient)
46 const stringified = JSON.stringify(dehydrated)
47β
48 // ---
49β
50 const parsed = JSON.parse(stringified)
51 const hydrationCache = new QueryCache()
52 const hydrationClient = createQueryClient({
53 queryCache: hydrationCache,
54 })
55 hydrate(hydrationClient, parsed)
56 expect(hydrationCache.find({ queryKey: ['string'] })?.state.data).toBe(
57 'string',
58 )
59 expect(hydrationCache.find({ queryKey: ['number'] })?.state.data).toBe(1)
60 expect(hydrationCache.find({ queryKey: ['boolean'] })?.state.data).toBe(
61 true,
62 )
63 expect(hydrationCache.find({ queryKey: ['null'] })?.state.data).toBe(null)
64 expect(hydrationCache.find({ queryKey: ['array'] })?.state.data).toEqual([
65 'string',
66 0,
67 ])
68 expect(hydrationCache.find({ queryKey: ['nested'] })?.state.data).toEqual({
69 key: [{ nestedKey: 1 }],
70 })
71β
72 const fetchDataAfterHydration = vi.fn<Array<unknown>, unknown>()
73 await hydrationClient.prefetchQuery({
74 queryKey: ['string'],
75 queryFn: fetchDataAfterHydration,
76 staleTime: 1000,
77 })
78 await hydrationClient.prefetchQuery({
79 queryKey: ['number'],
80 queryFn: fetchDataAfterHydration,
81 staleTime: 1000,
82 })
83 await hydrationClient.prefetchQuery({
84 queryKey: ['boolean'],
85 queryFn: fetchDataAfterHydration,
86 staleTime: 1000,
87 })
88 await hydrationClient.prefetchQuery({
89 queryKey: ['null'],
90 queryFn: fetchDataAfterHydration,
91 staleTime: 1000,
92 })
93 await hydrationClient.prefetchQuery({
94 queryKey: ['array'],
95 queryFn: fetchDataAfterHydration,
96 staleTime: 1000,
97 })
98 await hydrationClient.prefetchQuery({
99 queryKey: ['nested'],
100 queryFn: fetchDataAfterHydration,
101 staleTime: 1000,
102 })
103 expect(fetchDataAfterHydration).toHaveBeenCalledTimes(0)
104β
105 queryClient.clear()
106 hydrationClient.clear()
107 })
108β
109 test('should not dehydrate queries if dehydrateQueries is set to false', async () => {
110 const queryCache = new QueryCache()
111 const queryClient = createQueryClient({ queryCache })
112 await queryClient.prefetchQuery({
113 queryKey: ['string'],
114 queryFn: () => fetchData('string'),
115 })
116β
117 const dehydrated = dehydrate(queryClient, {
118 shouldDehydrateQuery: () => false,
119 })
120β
121 expect(dehydrated.queries.length).toBe(0)
122β
123 queryClient.clear()
124 })
125β
126 test('should use the garbage collection time from the client', async () => {
127 const queryCache = new QueryCache()
128 const queryClient = createQueryClient({ queryCache })
129 await queryClient.prefetchQuery({
130 queryKey: ['string'],
131 queryFn: () => fetchData('string'),
132 gcTime: 50,
133 })
134 const dehydrated = dehydrate(queryClient)
135 const stringified = JSON.stringify(dehydrated)
136β
137 await sleep(20)
138β
139 // ---
140β
141 const parsed = JSON.parse(stringified)
142 const hydrationCache = new QueryCache()
143 const hydrationClient = createQueryClient({ queryCache: hydrationCache })
144 hydrate(hydrationClient, parsed)
145 expect(hydrationCache.find({ queryKey: ['string'] })?.state.data).toBe(
146 'string',
147 )
148 await sleep(100)
149 expect(hydrationCache.find({ queryKey: ['string'] })).toBeTruthy()
150β
151 queryClient.clear()
152 hydrationClient.clear()
153 })
154β
155 test('should be able to provide default options for the hydrated queries', async () => {
156 const queryCache = new QueryCache()
157 const queryClient = createQueryClient({ queryCache })
158 await queryClient.prefetchQuery({
159 queryKey: ['string'],
160 queryFn: () => fetchData('string'),
161 })
162 const dehydrated = dehydrate(queryClient)
163 const stringified = JSON.stringify(dehydrated)
164 const parsed = JSON.parse(stringified)
165 const hydrationCache = new QueryCache()
166 const hydrationClient = createQueryClient({ queryCache: hydrationCache })
167 hydrate(hydrationClient, parsed, {
168 defaultOptions: { queries: { retry: 10 } },
169 })
170 expect(hydrationCache.find({ queryKey: ['string'] })?.options.retry).toBe(
171 10,
172 )
173 queryClient.clear()
174 hydrationClient.clear()
175 })
176β
177 test('should work with complex keys', async () => {
178 const queryCache = new QueryCache()
179 const queryClient = createQueryClient({ queryCache })
180 await queryClient.prefetchQuery({
181 queryKey: ['string', { key: ['string'], key2: 0 }],
182 queryFn: () => fetchData('string'),
183 })
184 const dehydrated = dehydrate(queryClient)
185 const stringified = JSON.stringify(dehydrated)
186β
187 // ---
188β
189 const parsed = JSON.parse(stringified)
190 const hydrationCache = new QueryCache()
191 const hydrationClient = createQueryClient({ queryCache: hydrationCache })
192 hydrate(hydrationClient, parsed)
193 expect(
194 hydrationCache.find({
195 queryKey: ['string', { key: ['string'], key2: 0 }],
196 })?.state.data,
197 ).toBe('string')
198β
199 const fetchDataAfterHydration = vi.fn<Array<unknown>, unknown>()
200 await hydrationClient.prefetchQuery({
201 queryKey: ['string', { key: ['string'], key2: 0 }],
202 queryFn: fetchDataAfterHydration,
203 staleTime: 100,
204 })
205 expect(fetchDataAfterHydration).toHaveBeenCalledTimes(0)
206β
207 queryClient.clear()
208 hydrationClient.clear()
209 })
210β
211 test('should only hydrate successful queries by default', async () => {
212 const consoleMock = vi.spyOn(console, 'error')
213 consoleMock.mockImplementation(() => undefined)
214β
215 const queryCache = new QueryCache()
216 const queryClient = createQueryClient({ queryCache })
217 await queryClient.prefetchQuery({
218 queryKey: ['success'],
219 queryFn: () => fetchData('success'),
220 })
221 queryClient.prefetchQuery({
222 queryKey: ['loading'],
223 queryFn: () => fetchData('loading', 10000),
224 })
225 await queryClient.prefetchQuery({
226 queryKey: ['error'],
227 queryFn: () => {
228 throw new Error()
229 },
230 })
231 const dehydrated = dehydrate(queryClient)
232 const stringified = JSON.stringify(dehydrated)
233β
234 // ---
235β
236 const parsed = JSON.parse(stringified)
237 const hydrationCache = new QueryCache()
238 const hydrationClient = createQueryClient({ queryCache: hydrationCache })
239 hydrate(hydrationClient, parsed)
240β
241 expect(hydrationCache.find({ queryKey: ['success'] })).toBeTruthy()
242 expect(hydrationCache.find({ queryKey: ['loading'] })).toBeFalsy()
243 expect(hydrationCache.find({ queryKey: ['error'] })).toBeFalsy()
244β
245 queryClient.clear()
246 hydrationClient.clear()
247 consoleMock.mockRestore()
248 })
249β
250 test('should filter queries via dehydrateQuery', async () => {
251 const queryCache = new QueryCache()
252 const queryClient = createQueryClient({ queryCache })
253 await queryClient.prefetchQuery({
254 queryKey: ['string'],
255 queryFn: () => fetchData('string'),
256 })
257 await queryClient.prefetchQuery({
258 queryKey: ['number'],
259 queryFn: () => fetchData(1),
260 })
261 const dehydrated = dehydrate(queryClient, {
262 shouldDehydrateQuery: (query) => query.queryKey[0] !== 'string',
263 })
264β
265 // This is testing implementation details that can change and are not
266 // part of the public API, but is important for keeping the payload small
267 const dehydratedQuery = dehydrated.queries.find(
268 (query) => query.queryKey[0] === 'string',
269 )
270 expect(dehydratedQuery).toBeUndefined()
271β
272 const stringified = JSON.stringify(dehydrated)
273β
274 // ---
275β
276 const parsed = JSON.parse(stringified)
277 const hydrationCache = new QueryCache()
278 const hydrationClient = createQueryClient({ queryCache: hydrationCache })
279 hydrate(hydrationClient, parsed)
280 expect(hydrationCache.find({ queryKey: ['string'] })).toBeUndefined()
281 expect(hydrationCache.find({ queryKey: ['number'] })?.state.data).toBe(1)
282β
283 queryClient.clear()
284 hydrationClient.clear()
285 })
286β
287 test('should not overwrite query in cache if hydrated query is older', async () => {
288 const queryCache = new QueryCache()
289 const queryClient = createQueryClient({ queryCache })
290 await queryClient.prefetchQuery({
291 queryKey: ['string'],
292 queryFn: () => fetchData('string-older', 5),
293 })
294 const dehydrated = dehydrate(queryClient)
295 const stringified = JSON.stringify(dehydrated)
296β
297 // ---
298β
299 const parsed = JSON.parse(stringified)
300 const hydrationCache = new QueryCache()
301 const hydrationClient = createQueryClient({ queryCache: hydrationCache })
302 await hydrationClient.prefetchQuery({
303 queryKey: ['string'],
304 queryFn: () => fetchData('string-newer', 5),
305 })
306β
307 hydrate(hydrationClient, parsed)
308 expect(hydrationCache.find({ queryKey: ['string'] })?.state.data).toBe(
309 'string-newer',
310 )
311β
312 queryClient.clear()
313 hydrationClient.clear()
314 })
315β
316 test('should overwrite query in cache if hydrated query is newer', async () => {
317 const hydrationCache = new QueryCache()
318 const hydrationClient = createQueryClient({ queryCache: hydrationCache })
319 await hydrationClient.prefetchQuery({
320 queryKey: ['string'],
321 queryFn: () => fetchData('string-older', 5),
322 })
323β
324 // ---
325β
326 const queryCache = new QueryCache()
327 const queryClient = createQueryClient({ queryCache })
328 await queryClient.prefetchQuery({
329 queryKey: ['string'],
330 queryFn: () => fetchData('string-newer', 5),
331 })
332 const dehydrated = dehydrate(queryClient)
333 const stringified = JSON.stringify(dehydrated)
334β
335 // ---
336β
337 const parsed = JSON.parse(stringified)
338 hydrate(hydrationClient, parsed)
339 expect(hydrationCache.find({ queryKey: ['string'] })?.state.data).toBe(
340 'string-newer',
341 )
342β
343 queryClient.clear()
344 hydrationClient.clear()
345 })
346β
347 test('should be able to dehydrate mutations and continue on hydration', async () => {
348 const consoleMock = vi.spyOn(console, 'error')
349 consoleMock.mockImplementation(() => undefined)
350 const onlineMock = mockOnlineManagerIsOnline(false)
351β
352 const serverAddTodo = vi
353 .fn()
354 .mockImplementation(() => Promise.reject(new Error('offline')))
355 const serverOnMutate = vi.fn().mockImplementation((variables) => {
356 const optimisticTodo = { id: 1, text: variables.text }
357 return { optimisticTodo }
358 })
359 const serverOnSuccess = vi.fn()
360β
361 const serverClient = createQueryClient()
362β
363 serverClient.setMutationDefaults(['addTodo'], {
364 mutationFn: serverAddTodo,
365 onMutate: serverOnMutate,
366 onSuccess: serverOnSuccess,
367 retry: 3,
368 retryDelay: 10,
369 })
370β
371 executeMutation(
372 serverClient,
373 {
374 mutationKey: ['addTodo'],
375 },
376 { text: 'text' },
377 ).catch(() => undefined)
378β
379 await sleep(50)
380β
381 const dehydrated = dehydrate(serverClient)
382 const stringified = JSON.stringify(dehydrated)
383β
384 serverClient.clear()
385β
386 // ---
387β
388 onlineMock.mockReturnValue(true)
389β
390 const parsed = JSON.parse(stringified)
391 const client = createQueryClient()
392β
393 const clientAddTodo = vi.fn().mockImplementation((variables) => {
394 return { id: 2, text: variables.text }
395 })
396 const clientOnMutate = vi.fn().mockImplementation((variables) => {
397 const optimisticTodo = { id: 1, text: variables.text }
398 return { optimisticTodo }
399 })
400 const clientOnSuccess = vi.fn()
401β
402 client.setMutationDefaults(['addTodo'], {
403 mutationFn: clientAddTodo,
404 onMutate: clientOnMutate,
405 onSuccess: clientOnSuccess,
406 retry: 3,
407 retryDelay: 10,
408 })
409β
410 hydrate(client, parsed)
411β
412 await client.resumePausedMutations()
413β
414 expect(clientAddTodo).toHaveBeenCalledTimes(1)
415 expect(clientOnMutate).not.toHaveBeenCalled()
416 expect(clientOnSuccess).toHaveBeenCalledTimes(1)
417 expect(clientOnSuccess).toHaveBeenCalledWith(
418 { id: 2, text: 'text' },
419 { text: 'text' },
420 { optimisticTodo: { id: 1, text: 'text' } },
421 )
422β
423 client.clear()
424 consoleMock.mockRestore()
425 onlineMock.mockRestore()
426 })
427β
428 test('should not dehydrate mutations if dehydrateMutations is set to false', async () => {
429 const consoleMock = vi.spyOn(console, 'error')
430 consoleMock.mockImplementation(() => undefined)
431β
432 const serverAddTodo = vi
433 .fn()
434 .mockImplementation(() => Promise.reject(new Error('offline')))
435β
436 const queryClient = createQueryClient()
437β
438 queryClient.setMutationDefaults(['addTodo'], {
439 mutationFn: serverAddTodo,
440 retry: false,
441 })
442β
443 executeMutation(
444 queryClient,
445 {
446 mutationKey: ['addTodo'],
447 },
448 { text: 'text' },
449 ).catch(() => undefined)
450β
451 await sleep(1)
452 const dehydrated = dehydrate(queryClient, {
453 shouldDehydrateMutation: () => false,
454 })
455β
456 expect(dehydrated.mutations.length).toBe(0)
457β
458 queryClient.clear()
459 consoleMock.mockRestore()
460 })
461β
462 test('should not dehydrate mutation if mutation state is set to pause', async () => {
463 const consoleMock = vi.spyOn(console, 'error')
464 consoleMock.mockImplementation(() => undefined)
465β
466 const serverAddTodo = vi
467 .fn()
468 .mockImplementation(() => Promise.reject(new Error('offline')))
469β
470 const queryClient = createQueryClient()
471β
472 queryClient.setMutationDefaults(['addTodo'], {
473 mutationFn: serverAddTodo,
474 retry: 1,
475 retryDelay: 20,
476 })
477β
478 executeMutation(
479 queryClient,
480 {
481 mutationKey: ['addTodo'],
482 },
483 { text: 'text' },
484 ).catch(() => undefined)
485β
486 // Dehydrate mutation between retries
487 await sleep(1)
488 const dehydrated = dehydrate(queryClient)
489β
490 expect(dehydrated.mutations.length).toBe(0)
491β
492 await sleep(30)
493 queryClient.clear()
494 consoleMock.mockRestore()
495 })
496β
497 test('should not hydrate if the hydratedState is null or is not an object', async () => {
498 const queryCache = new QueryCache()
499 const queryClient = createQueryClient({ queryCache })
500β
501 expect(() => hydrate(queryClient, null)).not.toThrow()
502 expect(() => hydrate(queryClient, 'invalid')).not.toThrow()
503β
504 queryClient.clear()
505 })
506β
507 test('should support hydratedState with undefined queries and mutations', async () => {
508 const queryCache = new QueryCache()
509 const queryClient = createQueryClient({ queryCache })
510β
511 expect(() => hydrate(queryClient, {})).not.toThrow()
512 expect(() => hydrate(queryClient, {})).not.toThrow()
513β
514 queryClient.clear()
515 })
516β
517 test('should set the fetchStatus to idle when creating a query with dehydrate', async () => {
518 const queryCache = new QueryCache()
519 const queryClient = createQueryClient({ queryCache })
520β
521 let isInitialFetch = true
522 let resolvePromise: (value: unknown) => void = () => undefined
523β
524 const customFetchData = () => {
525 const promise = new Promise((resolve) => {
526 resolvePromise = resolve
527 })
528 // Resolve the promise in initial fetch
529 // because we are awaiting the query first time
530 if (isInitialFetch) {
531 resolvePromise('string')
532 }
533 isInitialFetch = false
534 return promise
535 }
536β
537 await queryClient.prefetchQuery({
538 queryKey: ['string'],
539 queryFn: () => customFetchData(),
540 })
541β
542 queryClient.refetchQueries({ queryKey: ['string'] })
543β
544 const dehydrated = dehydrate(queryClient)
545 resolvePromise('string')
546 expect(
547 dehydrated.queries.find((q) => q.queryHash === '["string"]')?.state
548 .fetchStatus,
549 ).toBe('fetching')
550 const stringified = JSON.stringify(dehydrated)
551β
552 // ---
553 const parsed = JSON.parse(stringified)
554 const hydrationCache = new QueryCache()
555 const hydrationClient = createQueryClient({ queryCache: hydrationCache })
556 hydrate(hydrationClient, parsed)
557 expect(
558 hydrationCache.find({ queryKey: ['string'] })?.state.fetchStatus,
559 ).toBe('idle')
560 })
561β
562 test('should dehydrate and hydrate meta for queries', async () => {
563 const queryCache = new QueryCache()
564 const queryClient = createQueryClient({ queryCache })
565 await queryClient.prefetchQuery({
566 queryKey: ['meta'],
567 queryFn: () => Promise.resolve('meta'),
568 meta: {
569 some: 'meta',
570 },
571 })
572 await queryClient.prefetchQuery({
573 queryKey: ['no-meta'],
574 queryFn: () => Promise.resolve('no-meta'),
575 })
576β
577 const dehydrated = dehydrate(queryClient)
578β
579 expect(
580 dehydrated.queries.find((q) => q.queryHash === '["meta"]')?.meta,
581 ).toEqual({
582 some: 'meta',
583 })
584β
585 expect(
586 dehydrated.queries.find((q) => q.queryHash === '["no-meta"]')?.meta,
587 ).toEqual(undefined)
588β
589 expect(
590 Object.keys(
591 dehydrated.queries.find((q) => q.queryHash === '["no-meta"]')!,
592 ),
593 ).not.toEqual(expect.arrayContaining(['meta']))
594β
595 const stringified = JSON.stringify(dehydrated)
596β
597 // ---
598β
599 const parsed = JSON.parse(stringified)
600 const hydrationCache = new QueryCache()
601 const hydrationClient = createQueryClient({
602 queryCache: hydrationCache,
603 })
604 hydrate(hydrationClient, parsed)
605 expect(hydrationCache.find({ queryKey: ['meta'] })?.meta).toEqual({
606 some: 'meta',
607 })
608 expect(hydrationCache.find({ queryKey: ['no-meta'] })?.meta).toEqual(
609 undefined,
610 )
611 })
612β
613 test('should dehydrate and hydrate meta for mutations', async () => {
614 const mutationCache = new MutationCache()
615 const queryClient = createQueryClient({ mutationCache })
616β
617 await executeMutation(
618 queryClient,
619 {
620 mutationKey: ['meta'],
621 mutationFn: () => Promise.resolve('meta'),
622 meta: {
623 some: 'meta',
624 },
625 },
626 undefined,
627 )
628β
629 await executeMutation(
630 queryClient,
631 {
632 mutationKey: ['no-meta'],
633 mutationFn: () => Promise.resolve('no-meta'),
634 },
635 undefined,
636 )
637β
638 const dehydrated = dehydrate(queryClient, {
639 shouldDehydrateMutation: () => true,
640 })
641β
642 expect(Object.keys(dehydrated.mutations[0]!)).toEqual(
643 expect.arrayContaining(['meta']),
644 )
645 expect(dehydrated.mutations[0]?.meta).toEqual({
646 some: 'meta',
647 })
648β
649 expect(Object.keys(dehydrated.mutations[1]!)).not.toEqual(
650 expect.arrayContaining(['meta']),
651 )
652 expect(dehydrated.mutations[1]?.meta).toEqual(undefined)
653β
654 const stringified = JSON.stringify(dehydrated)
655β
656 // ---
657β
658 const parsed = JSON.parse(stringified)
659 const hydrationCache = new MutationCache()
660 const hydrationClient = createQueryClient({
661 mutationCache: hydrationCache,
662 })
663 hydrate(hydrationClient, parsed)
664 expect(hydrationCache.find({ mutationKey: ['meta'] })?.meta).toEqual({
665 some: 'meta',
666 })
667 expect(hydrationCache.find({ mutationKey: ['no-meta'] })?.meta).toEqual(
668 undefined,
669 )
670 })
671β
672 test('should not change fetchStatus when updating a query with dehydrate', async () => {
673 const queryClient = createQueryClient()
674β
675 const options = {
676 queryKey: ['string'],
677 queryFn: async () => {
678 await sleep(10)
679 return 'string'
680 },
681 } as const
682β
683 await queryClient.prefetchQuery(options)
684β
685 const dehydrated = dehydrate(queryClient)
686 expect(
687 dehydrated.queries.find((q) => q.queryHash === '["string"]')?.state
688 .fetchStatus,
689 ).toBe('idle')
690 const stringified = JSON.stringify(dehydrated)
691β
692 // ---
693 const parsed = JSON.parse(stringified)
694 const hydrationCache = new QueryCache()
695 const hydrationClient = createQueryClient({ queryCache: hydrationCache })
696β
697 const promise = hydrationClient.prefetchQuery(options)
698 hydrate(hydrationClient, parsed)
699 expect(
700 hydrationCache.find({ queryKey: ['string'] })?.state.fetchStatus,
701 ).toBe('fetching')
702 await promise
703 expect(
704 hydrationCache.find({ queryKey: ['string'] })?.state.fetchStatus,
705 ).toBe('idle')
706 })
707})