Open History to see the last commit
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 use the cache time from the client', async () => {
67 const queryCache = new QueryCache()
68 const queryClient = new QueryClient({ queryCache })
69 await queryClient.prefetchQuery('string', () => fetchData('string'), {
70 cacheTime: 50,
71 })
72 const dehydrated = dehydrate(queryClient)
73 const stringified = JSON.stringify(dehydrated)
74β
75 await sleep(20)
76β
77 // ---
78β
79 const parsed = JSON.parse(stringified)
80 const hydrationCache = new QueryCache()
81 const hydrationClient = new QueryClient({ queryCache: hydrationCache })
82 hydrate(hydrationClient, parsed)
83 expect(hydrationCache.find('string')?.state.data).toBe('string')
84 await sleep(100)
85 expect(hydrationCache.find('string')).toBeTruthy()
86β
87 queryClient.clear()
88 hydrationClient.clear()
89 })
90β
91 test('should be able to provide default options for the hydrated queries', async () => {
92 const queryCache = new QueryCache()
93 const queryClient = new QueryClient({ queryCache })
94 await queryClient.prefetchQuery('string', () => fetchData('string'))
95 const dehydrated = dehydrate(queryClient)
96 const stringified = JSON.stringify(dehydrated)
97 const parsed = JSON.parse(stringified)
98 const hydrationCache = new QueryCache()
99 const hydrationClient = new QueryClient({ queryCache: hydrationCache })
100 hydrate(hydrationClient, parsed, {
101 defaultOptions: { queries: { retry: 10 } },
102 })
103 expect(hydrationCache.find('string')?.options.retry).toBe(10)
104 queryClient.clear()
105 hydrationClient.clear()
106 })
107β
108 test('should work with complex keys', async () => {
109 const queryCache = new QueryCache()
110 const queryClient = new QueryClient({ queryCache })
111 await queryClient.prefetchQuery(
112 ['string', { key: ['string'], key2: 0 }],
113 () => fetchData('string')
114 )
115 const dehydrated = dehydrate(queryClient)
116 const stringified = JSON.stringify(dehydrated)
117β
118 // ---
119β
120 const parsed = JSON.parse(stringified)
121 const hydrationCache = new QueryCache()
122 const hydrationClient = new QueryClient({ queryCache: hydrationCache })
123 hydrate(hydrationClient, parsed)
124 expect(
125 hydrationCache.find(['string', { key: ['string'], key2: 0 }])?.state.data
126 ).toBe('string')
127β
128 const fetchDataAfterHydration = jest.fn()
129 await hydrationClient.prefetchQuery(
130 ['string', { key: ['string'], key2: 0 }],
131 fetchDataAfterHydration,
132 { staleTime: 100 }
133 )
134 expect(fetchDataAfterHydration).toHaveBeenCalledTimes(0)
135β
136 queryClient.clear()
137 hydrationClient.clear()
138 })
139β
140 test('should only hydrate successful queries by default', async () => {
141 const consoleMock = jest.spyOn(console, 'error')
142 consoleMock.mockImplementation(() => undefined)
143β
144 const queryCache = new QueryCache()
145 const queryClient = new QueryClient({ queryCache })
146 await queryClient.prefetchQuery('success', () => fetchData('success'))
147 queryClient.prefetchQuery('loading', () => fetchData('loading', 10000))
148 await queryClient.prefetchQuery('error', () => {
149 throw new Error()
150 })
151 const dehydrated = dehydrate(queryClient)
152 const stringified = JSON.stringify(dehydrated)
153β
154 // ---
155β
156 const parsed = JSON.parse(stringified)
157 const hydrationCache = new QueryCache()
158 const hydrationClient = new QueryClient({ queryCache: hydrationCache })
159 hydrate(hydrationClient, parsed)
160β
161 expect(hydrationCache.find('success')).toBeTruthy()
162 expect(hydrationCache.find('loading')).toBeFalsy()
163 expect(hydrationCache.find('error')).toBeFalsy()
164β
165 queryClient.clear()
166 hydrationClient.clear()
167 consoleMock.mockRestore()
168 })
169β
170 test('should filter queries via shouldDehydrateQuery', async () => {
171 const queryCache = new QueryCache()
172 const queryClient = new QueryClient({ queryCache })
173 await queryClient.prefetchQuery('string', () => fetchData('string'))
174 await queryClient.prefetchQuery('number', () => fetchData(1))
175 const dehydrated = dehydrate(queryClient, {
176 shouldDehydrateQuery: query => query.queryKey !== 'string',
177 })
178β
179 // This is testing implementation details that can change and are not
180 // part of the public API, but is important for keeping the payload small
181 const dehydratedQuery = dehydrated?.queries.find(
182 query => query?.queryKey === 'string'
183 )
184 expect(dehydratedQuery).toBeUndefined()
185β
186 const stringified = JSON.stringify(dehydrated)
187β
188 // ---
189β
190 const parsed = JSON.parse(stringified)
191 const hydrationCache = new QueryCache()
192 const hydrationClient = new QueryClient({ queryCache: hydrationCache })
193 hydrate(hydrationClient, parsed)
194 expect(hydrationCache.find('string')).toBeUndefined()
195 expect(hydrationCache.find('number')?.state.data).toBe(1)
196β
197 queryClient.clear()
198 hydrationClient.clear()
199 })
200β
201 test('should not overwrite query in cache if hydrated query is older', async () => {
202 const queryCache = new QueryCache()
203 const queryClient = new QueryClient({ queryCache })
204 await queryClient.prefetchQuery('string', () =>
205 fetchData('string-older', 5)
206 )
207 const dehydrated = dehydrate(queryClient)
208 const stringified = JSON.stringify(dehydrated)
209β
210 // ---
211β
212 const parsed = JSON.parse(stringified)
213 const hydrationCache = new QueryCache()
214 const hydrationClient = new QueryClient({ queryCache: hydrationCache })
215 await hydrationClient.prefetchQuery('string', () =>
216 fetchData('string-newer', 5)
217 )
218β
219 hydrate(hydrationClient, parsed)
220 expect(hydrationCache.find('string')?.state.data).toBe('string-newer')
221β
222 queryClient.clear()
223 hydrationClient.clear()
224 })
225β
226 test('should overwrite query in cache if hydrated query is newer', async () => {
227 const hydrationCache = new QueryCache()
228 const hydrationClient = new QueryClient({ queryCache: hydrationCache })
229 await hydrationClient.prefetchQuery('string', () =>
230 fetchData('string-older', 5)
231 )
232β
233 // ---
234β
235 const queryCache = new QueryCache()
236 const queryClient = new QueryClient({ queryCache })
237 await queryClient.prefetchQuery('string', () =>
238 fetchData('string-newer', 5)
239 )
240 const dehydrated = dehydrate(queryClient)
241 const stringified = JSON.stringify(dehydrated)
242β
243 // ---
244β
245 const parsed = JSON.parse(stringified)
246 hydrate(hydrationClient, parsed)
247 expect(hydrationCache.find('string')?.state.data).toBe('string-newer')
248β
249 queryClient.clear()
250 hydrationClient.clear()
251 })
252β
253 test('should be able to dehydrate mutations and continue on hydration', async () => {
254 const consoleMock = jest.spyOn(console, 'error')
255 consoleMock.mockImplementation(() => undefined)
256 mockNavigatorOnLine(false)
257β
258 const serverAddTodo = jest
259 .fn()
260 .mockImplementation(() => Promise.reject('offline'))
261 const serverOnMutate = jest.fn().mockImplementation(variables => {
262 const optimisticTodo = { id: 1, text: variables.text }
263 return { optimisticTodo }
264 })
265 const serverOnSuccess = jest.fn()
266β
267 const serverClient = new QueryClient()
268β
269 serverClient.setMutationDefaults('addTodo', {
270 mutationFn: serverAddTodo,
271 onMutate: serverOnMutate,
272 onSuccess: serverOnSuccess,
273 retry: 3,
274 retryDelay: 10,
275 })
276β
277 serverClient
278 .executeMutation({
279 mutationKey: 'addTodo',
280 variables: { text: 'text' },
281 })
282 .catch(() => undefined)
283β
284 await sleep(50)
285β
286 const dehydrated = dehydrate(serverClient)
287 const stringified = JSON.stringify(dehydrated)
288β
289 serverClient.clear()
290β
291 // ---
292β
293 mockNavigatorOnLine(true)
294β
295 const parsed = JSON.parse(stringified)
296 const client = new QueryClient()
297β
298 const clientAddTodo = jest.fn().mockImplementation(variables => {
299 return { id: 2, text: variables.text }
300 })
301 const clientOnMutate = jest.fn().mockImplementation(variables => {
302 const optimisticTodo = { id: 1, text: variables.text }
303 return { optimisticTodo }
304 })
305 const clientOnSuccess = jest.fn()
306β
307 client.setMutationDefaults('addTodo', {
308 mutationFn: clientAddTodo,
309 onMutate: clientOnMutate,
310 onSuccess: clientOnSuccess,
311 retry: 3,
312 retryDelay: 10,
313 })
314β
315 hydrate(client, parsed)
316β
317 await client.resumePausedMutations()
318β
319 expect(clientAddTodo).toHaveBeenCalledTimes(1)
320 expect(clientOnMutate).not.toHaveBeenCalled()
321 expect(clientOnSuccess).toHaveBeenCalledTimes(1)
322 expect(clientOnSuccess).toHaveBeenCalledWith(
323 { id: 2, text: 'text' },
324 { text: 'text' },
325 { optimisticTodo: { id: 1, text: 'text' } }
326 )
327β
328 client.clear()
329 consoleMock.mockRestore()
330 })
331})