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

hydration.test.tsx

428 lines13.6 KB

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