Open History to see the last commit
1import { QueryCache } from '../queryCache'
2import { dehydrate, hydrate } from '../hydration'
3import {
4 createQueryClient,
5 executeMutation,
6 mockNavigatorOnLine,
7 sleep,
8} from './utils'
9β
10async function fetchData<TData>(value: TData, ms?: number): Promise<TData> {
11 await sleep(ms || 0)
12 return value
13}
14β
15describe('dehydration and rehydration', () => {
16 test('should work with serializeable values', async () => {
17 const queryCache = new QueryCache()
18 const queryClient = createQueryClient({ queryCache })
19 await queryClient.prefetchQuery(['string'], () => fetchData('string'))
20 await queryClient.prefetchQuery(['number'], () => fetchData(1))
21 await queryClient.prefetchQuery(['boolean'], () => fetchData(true))
22 await queryClient.prefetchQuery(['null'], () => fetchData(null))
23 await queryClient.prefetchQuery(['array'], () => fetchData(['string', 0]))
24 await queryClient.prefetchQuery(['nested'], () =>
25 fetchData({ key: [{ nestedKey: 1 }] }),
26 )
27 const dehydrated = dehydrate(queryClient)
28 const stringified = JSON.stringify(dehydrated)
29β
30 // ---
31β
32 const parsed = JSON.parse(stringified)
33 const hydrationCache = new QueryCache()
34 const hydrationClient = createQueryClient({
35 queryCache: hydrationCache,
36 })
37 hydrate(hydrationClient, parsed)
38 expect(hydrationCache.find(['string'])?.state.data).toBe('string')
39 expect(hydrationCache.find(['number'])?.state.data).toBe(1)
40 expect(hydrationCache.find(['boolean'])?.state.data).toBe(true)
41 expect(hydrationCache.find(['null'])?.state.data).toBe(null)
42 expect(hydrationCache.find(['array'])?.state.data).toEqual(['string', 0])
43 expect(hydrationCache.find(['nested'])?.state.data).toEqual({
44 key: [{ nestedKey: 1 }],
45 })
46β
47 const fetchDataAfterHydration = jest.fn<unknown, unknown[]>()
48 await hydrationClient.prefetchQuery(['string'], fetchDataAfterHydration, {
49 staleTime: 1000,
50 })
51 await hydrationClient.prefetchQuery(['number'], fetchDataAfterHydration, {
52 staleTime: 1000,
53 })
54 await hydrationClient.prefetchQuery(['boolean'], fetchDataAfterHydration, {
55 staleTime: 1000,
56 })
57 await hydrationClient.prefetchQuery(['null'], fetchDataAfterHydration, {
58 staleTime: 1000,
59 })
60 await hydrationClient.prefetchQuery(['array'], fetchDataAfterHydration, {
61 staleTime: 1000,
62 })
63 await hydrationClient.prefetchQuery(['nested'], fetchDataAfterHydration, {
64 staleTime: 1000,
65 })
66 expect(fetchDataAfterHydration).toHaveBeenCalledTimes(0)
67β
68 queryClient.clear()
69 hydrationClient.clear()
70 })
71β
72 test('should not dehydrate queries if dehydrateQueries is set to false', async () => {
73 const queryCache = new QueryCache()
74 const queryClient = createQueryClient({ queryCache })
75 await queryClient.prefetchQuery(['string'], () => fetchData('string'))
76β
77 const dehydrated = dehydrate(queryClient, { dehydrateQueries: false })
78β
79 expect(dehydrated.queries.length).toBe(0)
80β
81 queryClient.clear()
82 })
83β
84 test('should use the cache time from the client', async () => {
85 const queryCache = new QueryCache()
86 const queryClient = createQueryClient({ queryCache })
87 await queryClient.prefetchQuery(['string'], () => fetchData('string'), {
88 cacheTime: 50,
89 })
90 const dehydrated = dehydrate(queryClient)
91 const stringified = JSON.stringify(dehydrated)
92β
93 await sleep(20)
94β
95 // ---
96β
97 const parsed = JSON.parse(stringified)
98 const hydrationCache = new QueryCache()
99 const hydrationClient = createQueryClient({ queryCache: hydrationCache })
100 hydrate(hydrationClient, parsed)
101 expect(hydrationCache.find(['string'])?.state.data).toBe('string')
102 await sleep(100)
103 expect(hydrationCache.find(['string'])).toBeTruthy()
104β
105 queryClient.clear()
106 hydrationClient.clear()
107 })
108β
109 test('should be able to provide default options for the hydrated queries', async () => {
110 const queryCache = new QueryCache()
111 const queryClient = createQueryClient({ queryCache })
112 await queryClient.prefetchQuery(['string'], () => fetchData('string'))
113 const dehydrated = dehydrate(queryClient)
114 const stringified = JSON.stringify(dehydrated)
115 const parsed = JSON.parse(stringified)
116 const hydrationCache = new QueryCache()
117 const hydrationClient = createQueryClient({ queryCache: hydrationCache })
118 hydrate(hydrationClient, parsed, {
119 defaultOptions: { queries: { retry: 10 } },
120 })
121 expect(hydrationCache.find(['string'])?.options.retry).toBe(10)
122 queryClient.clear()
123 hydrationClient.clear()
124 })
125β
126 test('should work with complex keys', async () => {
127 const queryCache = new QueryCache()
128 const queryClient = createQueryClient({ queryCache })
129 await queryClient.prefetchQuery(
130 ['string', { key: ['string'], key2: 0 }],
131 () => fetchData('string'),
132 )
133 const dehydrated = dehydrate(queryClient)
134 const stringified = JSON.stringify(dehydrated)
135β
136 // ---
137β
138 const parsed = JSON.parse(stringified)
139 const hydrationCache = new QueryCache()
140 const hydrationClient = createQueryClient({ queryCache: hydrationCache })
141 hydrate(hydrationClient, parsed)
142 expect(
143 hydrationCache.find(['string', { key: ['string'], key2: 0 }])?.state.data,
144 ).toBe('string')
145β
146 const fetchDataAfterHydration = jest.fn<unknown, unknown[]>()
147 await hydrationClient.prefetchQuery(
148 ['string', { key: ['string'], key2: 0 }],
149 fetchDataAfterHydration,
150 { staleTime: 100 },
151 )
152 expect(fetchDataAfterHydration).toHaveBeenCalledTimes(0)
153β
154 queryClient.clear()
155 hydrationClient.clear()
156 })
157β
158 test('should only hydrate successful queries by default', async () => {
159 const consoleMock = jest.spyOn(console, 'error')
160 consoleMock.mockImplementation(() => undefined)
161β
162 const queryCache = new QueryCache()
163 const queryClient = createQueryClient({ queryCache })
164 await queryClient.prefetchQuery(['success'], () => fetchData('success'))
165 queryClient.prefetchQuery(['loading'], () => fetchData('loading', 10000))
166 await queryClient.prefetchQuery(['error'], () => {
167 throw new Error()
168 })
169 const dehydrated = dehydrate(queryClient)
170 const stringified = JSON.stringify(dehydrated)
171β
172 // ---
173β
174 const parsed = JSON.parse(stringified)
175 const hydrationCache = new QueryCache()
176 const hydrationClient = createQueryClient({ queryCache: hydrationCache })
177 hydrate(hydrationClient, parsed)
178β
179 expect(hydrationCache.find(['success'])).toBeTruthy()
180 expect(hydrationCache.find(['loading'])).toBeFalsy()
181 expect(hydrationCache.find(['error'])).toBeFalsy()
182β
183 queryClient.clear()
184 hydrationClient.clear()
185 consoleMock.mockRestore()
186 })
187β
188 test('should filter queries via shouldDehydrateQuery', async () => {
189 const queryCache = new QueryCache()
190 const queryClient = createQueryClient({ queryCache })
191 await queryClient.prefetchQuery(['string'], () => fetchData('string'))
192 await queryClient.prefetchQuery(['number'], () => fetchData(1))
193 const dehydrated = dehydrate(queryClient, {
194 shouldDehydrateQuery: (query) => query.queryKey[0] !== 'string',
195 })
196β
197 // This is testing implementation details that can change and are not
198 // part of the public API, but is important for keeping the payload small
199 const dehydratedQuery = dehydrated.queries.find(
200 (query) => query.queryKey[0] === 'string',
201 )
202 expect(dehydratedQuery).toBeUndefined()
203β
204 const stringified = JSON.stringify(dehydrated)
205β
206 // ---
207β
208 const parsed = JSON.parse(stringified)
209 const hydrationCache = new QueryCache()
210 const hydrationClient = createQueryClient({ queryCache: hydrationCache })
211 hydrate(hydrationClient, parsed)
212 expect(hydrationCache.find(['string'])).toBeUndefined()
213 expect(hydrationCache.find(['number'])?.state.data).toBe(1)
214β
215 queryClient.clear()
216 hydrationClient.clear()
217 })
218β
219 test('should not overwrite query in cache if hydrated query is older', async () => {
220 const queryCache = new QueryCache()
221 const queryClient = createQueryClient({ queryCache })
222 await queryClient.prefetchQuery(['string'], () =>
223 fetchData('string-older', 5),
224 )
225 const dehydrated = dehydrate(queryClient)
226 const stringified = JSON.stringify(dehydrated)
227β
228 // ---
229β
230 const parsed = JSON.parse(stringified)
231 const hydrationCache = new QueryCache()
232 const hydrationClient = createQueryClient({ queryCache: hydrationCache })
233 await hydrationClient.prefetchQuery(['string'], () =>
234 fetchData('string-newer', 5),
235 )
236β
237 hydrate(hydrationClient, parsed)
238 expect(hydrationCache.find(['string'])?.state.data).toBe('string-newer')
239β
240 queryClient.clear()
241 hydrationClient.clear()
242 })
243β
244 test('should overwrite query in cache if hydrated query is newer', async () => {
245 const hydrationCache = new QueryCache()
246 const hydrationClient = createQueryClient({ queryCache: hydrationCache })
247 await hydrationClient.prefetchQuery(['string'], () =>
248 fetchData('string-older', 5),
249 )
250β
251 // ---
252β
253 const queryCache = new QueryCache()
254 const queryClient = createQueryClient({ queryCache })
255 await queryClient.prefetchQuery(['string'], () =>
256 fetchData('string-newer', 5),
257 )
258 const dehydrated = dehydrate(queryClient)
259 const stringified = JSON.stringify(dehydrated)
260β
261 // ---
262β
263 const parsed = JSON.parse(stringified)
264 hydrate(hydrationClient, parsed)
265 expect(hydrationCache.find(['string'])?.state.data).toBe('string-newer')
266β
267 queryClient.clear()
268 hydrationClient.clear()
269 })
270β
271 test('should be able to dehydrate mutations and continue on hydration', async () => {
272 const consoleMock = jest.spyOn(console, 'error')
273 consoleMock.mockImplementation(() => undefined)
274 const onlineMock = mockNavigatorOnLine(false)
275β
276 const serverAddTodo = jest
277 .fn()
278 .mockImplementation(() => Promise.reject('offline'))
279 const serverOnMutate = jest.fn().mockImplementation((variables) => {
280 const optimisticTodo = { id: 1, text: variables.text }
281 return { optimisticTodo }
282 })
283 const serverOnSuccess = jest.fn()
284β
285 const serverClient = createQueryClient()
286β
287 serverClient.setMutationDefaults(['addTodo'], {
288 mutationFn: serverAddTodo,
289 onMutate: serverOnMutate,
290 onSuccess: serverOnSuccess,
291 retry: 3,
292 retryDelay: 10,
293 })
294β
295 executeMutation(serverClient, {
296 mutationKey: ['addTodo'],
297 variables: { text: 'text' },
298 }).catch(() => undefined)
299β
300 await sleep(50)
301β
302 const dehydrated = dehydrate(serverClient)
303 const stringified = JSON.stringify(dehydrated)
304β
305 serverClient.clear()
306β
307 // ---
308β
309 onlineMock.mockReturnValue(true)
310β
311 const parsed = JSON.parse(stringified)
312 const client = createQueryClient()
313β
314 const clientAddTodo = jest.fn().mockImplementation((variables) => {
315 return { id: 2, text: variables.text }
316 })
317 const clientOnMutate = jest.fn().mockImplementation((variables) => {
318 const optimisticTodo = { id: 1, text: variables.text }
319 return { optimisticTodo }
320 })
321 const clientOnSuccess = jest.fn()
322β
323 client.setMutationDefaults(['addTodo'], {
324 mutationFn: clientAddTodo,
325 onMutate: clientOnMutate,
326 onSuccess: clientOnSuccess,
327 retry: 3,
328 retryDelay: 10,
329 })
330β
331 hydrate(client, parsed)
332β
333 await client.resumePausedMutations()
334β
335 expect(clientAddTodo).toHaveBeenCalledTimes(1)
336 expect(clientOnMutate).not.toHaveBeenCalled()
337 expect(clientOnSuccess).toHaveBeenCalledTimes(1)
338 expect(clientOnSuccess).toHaveBeenCalledWith(
339 { id: 2, text: 'text' },
340 { text: 'text' },
341 { optimisticTodo: { id: 1, text: 'text' } },
342 )
343β
344 client.clear()
345 consoleMock.mockRestore()
346 onlineMock.mockRestore()
347 })
348β
349 test('should not dehydrate mutations if dehydrateMutations is set to false', async () => {
350 const consoleMock = jest.spyOn(console, 'error')
351 consoleMock.mockImplementation(() => undefined)
352β
353 const serverAddTodo = jest
354 .fn()
355 .mockImplementation(() => Promise.reject('offline'))
356β
357 const queryClient = createQueryClient()
358β
359 queryClient.setMutationDefaults(['addTodo'], {
360 mutationFn: serverAddTodo,
361 retry: false,
362 })
363β
364 executeMutation(queryClient, {
365 mutationKey: ['addTodo'],
366 variables: { text: 'text' },
367 }).catch(() => undefined)
368β
369 await sleep(1)
370 const dehydrated = dehydrate(queryClient, { dehydrateMutations: false })
371β
372 expect(dehydrated.mutations.length).toBe(0)
373β
374 queryClient.clear()
375 consoleMock.mockRestore()
376 })
377β
378 test('should not dehydrate mutation if mutation state is set to pause', async () => {
379 const consoleMock = jest.spyOn(console, 'error')
380 consoleMock.mockImplementation(() => undefined)
381β
382 const serverAddTodo = jest
383 .fn()
384 .mockImplementation(() => Promise.reject('offline'))
385β
386 const queryClient = createQueryClient()
387β
388 queryClient.setMutationDefaults(['addTodo'], {
389 mutationFn: serverAddTodo,
390 retry: 1,
391 retryDelay: 20,
392 })
393β
394 executeMutation(queryClient, {
395 mutationKey: ['addTodo'],
396 variables: { text: 'text' },
397 }).catch(() => undefined)
398β
399 // Dehydrate mutation between retries
400 await sleep(1)
401 const dehydrated = dehydrate(queryClient)
402β
403 expect(dehydrated.mutations.length).toBe(0)
404β
405 await sleep(30)
406 queryClient.clear()
407 consoleMock.mockRestore()
408 })
409β
410 test('should not hydrate if the hydratedState is null or is not an object', async () => {
411 const queryCache = new QueryCache()
412 const queryClient = createQueryClient({ queryCache })
413β
414 expect(() => hydrate(queryClient, null)).not.toThrow()
415 expect(() => hydrate(queryClient, 'invalid')).not.toThrow()
416β
417 queryClient.clear()
418 })
419β
420 test('should support hydratedState with undefined queries and mutations', async () => {
421 const queryCache = new QueryCache()
422 const queryClient = createQueryClient({ queryCache })
423β
424 expect(() => hydrate(queryClient, {})).not.toThrow()
425 expect(() => hydrate(queryClient, {})).not.toThrow()
426β
427 queryClient.clear()
428 })
429β
430 test('should set the fetchStatus to idle when creating a query with dehydrate', async () => {
431 const queryCache = new QueryCache()
432 const queryClient = createQueryClient({ queryCache })
433β
434 let isInitialFetch = true
435 let resolvePromise: (value: unknown) => void = () => undefined
436β
437 const customFetchData = () => {
438 const promise = new Promise((resolve) => {
439 resolvePromise = resolve
440 })
441 // Resolve the promise in initial fetch
442 // because we are awaiting the query first time
443 if (isInitialFetch) {
444 resolvePromise('string')
445 }
446 isInitialFetch = false
447 return promise
448 }
449β
450 await queryClient.prefetchQuery(['string'], () => customFetchData())
451β
452 queryClient.refetchQueries(['string'])
453β
454 const dehydrated = dehydrate(queryClient)
455 resolvePromise('string')
456 expect(
457 dehydrated.queries.find((q) => q.queryHash === '["string"]')?.state
458 .fetchStatus,
459 ).toBe('fetching')
460 const stringified = JSON.stringify(dehydrated)
461β
462 // ---
463 const parsed = JSON.parse(stringified)
464 const hydrationCache = new QueryCache()
465 const hydrationClient = createQueryClient({ queryCache: hydrationCache })
466 hydrate(hydrationClient, parsed)
467 expect(hydrationCache.find(['string'])?.state.fetchStatus).toBe('idle')
468 })
469β
470 test('should not change fetchStatus when updating a query with dehydrate', async () => {
471 const queryClient = createQueryClient()
472β
473 const options = {
474 queryKey: ['string'],
475 queryFn: async () => {
476 await sleep(10)
477 return 'string'
478 },
479 } as const
480β
481 await queryClient.prefetchQuery(options)
482β
483 const dehydrated = dehydrate(queryClient)
484 expect(
485 dehydrated.queries.find((q) => q.queryHash === '["string"]')?.state
486 .fetchStatus,
487 ).toBe('idle')
488 const stringified = JSON.stringify(dehydrated)
489β
490 // ---
491 const parsed = JSON.parse(stringified)
492 const hydrationCache = new QueryCache()
493 const hydrationClient = createQueryClient({ queryCache: hydrationCache })
494β
495 const promise = hydrationClient.prefetchQuery(options)
496 hydrate(hydrationClient, parsed)
497 expect(hydrationCache.find(['string'])?.state.fetchStatus).toBe('fetching')
498 await promise
499 expect(hydrationCache.find(['string'])?.state.fetchStatus).toBe('idle')
500 })
501})