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

hydration.test.tsx

330 lines10.8 KB

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