Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
2import { queryKey, sleep } from '@tanstack/query-test-utils'
3import { MutationCache, MutationObserver, QueryClient } from '..'
4import { executeMutation } from './utils'
5β
6describe('mutationCache', () => {
7 beforeEach(() => {
8 vi.useFakeTimers()
9 })
10β
11 afterEach(() => {
12 vi.useRealTimers()
13 })
14β
15 describe('MutationCacheConfig error callbacks', () => {
16 test('should call onError and onSettled when a mutation errors', async () => {
17 const key = queryKey()
18 const onError = vi.fn()
19 const onSuccess = vi.fn()
20 const onSettled = vi.fn()
21 const testCache = new MutationCache({ onError, onSuccess, onSettled })
22 const testClient = new QueryClient({ mutationCache: testCache })
23β
24 executeMutation(
25 testClient,
26 {
27 mutationKey: key,
28 mutationFn: () =>
29 sleep(10).then(() => Promise.reject(new Error('error'))),
30 onMutate: () => 'result',
31 },
32 'vars',
33 ).catch(() => undefined)
34 await vi.advanceTimersByTimeAsync(10)
35β
36 const mutation = testCache.getAll()[0]
37β
38 expect(onError).toHaveBeenCalledTimes(1)
39 expect(onError).toHaveBeenCalledWith(
40 new Error('error'),
41 'vars',
42 'result',
43 mutation,
44 {
45 client: testClient,
46 meta: undefined,
47 mutationKey: key,
48 },
49 )
50 expect(onSuccess).not.toHaveBeenCalled()
51 expect(onSettled).toHaveBeenCalledTimes(1)
52 expect(onSettled).toHaveBeenCalledWith(
53 undefined,
54 new Error('error'),
55 'vars',
56 'result',
57 mutation,
58 {
59 client: testClient,
60 meta: undefined,
61 mutationKey: key,
62 },
63 )
64 })
65β
66 test('should be awaited', async () => {
67 const key = queryKey()
68 const states: Array<number> = []
69 const onError = () =>
70 sleep(10).then(() => {
71 states.push(1)
72 states.push(2)
73 })
74 const onSettled = () =>
75 sleep(10).then(() => {
76 states.push(5)
77 states.push(6)
78 })
79β
80 const testCache = new MutationCache({ onError, onSettled })
81 const testClient = new QueryClient({ mutationCache: testCache })
82β
83 executeMutation(
84 testClient,
85 {
86 mutationKey: key,
87 mutationFn: () =>
88 sleep(10).then(() => Promise.reject(new Error('error'))),
89 onError: () =>
90 sleep(10).then(() => {
91 states.push(3)
92 states.push(4)
93 }),
94 onSettled: () =>
95 sleep(10).then(() => {
96 states.push(7)
97 states.push(8)
98 }),
99 },
100 'vars',
101 ).catch(() => undefined)
102 await vi.advanceTimersByTimeAsync(50)
103β
104 expect(states).toEqual([1, 2, 3, 4, 5, 6, 7, 8])
105 })
106 })
107β
108 describe('MutationCacheConfig success callbacks', () => {
109 test('should call onSuccess and onSettled when a mutation is successful', async () => {
110 const key = queryKey()
111 const onError = vi.fn()
112 const onSuccess = vi.fn()
113 const onSettled = vi.fn()
114 const testCache = new MutationCache({ onError, onSuccess, onSettled })
115 const testClient = new QueryClient({ mutationCache: testCache })
116β
117 executeMutation(
118 testClient,
119 {
120 mutationKey: key,
121 mutationFn: () => sleep(10).then(() => ({ data: 5 })),
122 onMutate: () => 'result',
123 },
124 'vars',
125 )
126 await vi.advanceTimersByTimeAsync(10)
127β
128 const mutation = testCache.getAll()[0]
129β
130 expect(onSuccess).toHaveBeenCalledTimes(1)
131 expect(onSuccess).toHaveBeenCalledWith(
132 { data: 5 },
133 'vars',
134 'result',
135 mutation,
136 {
137 client: testClient,
138 meta: undefined,
139 mutationKey: key,
140 },
141 )
142 expect(onError).not.toHaveBeenCalled()
143 expect(onSettled).toHaveBeenCalledTimes(1)
144 expect(onSettled).toHaveBeenCalledWith(
145 { data: 5 },
146 null,
147 'vars',
148 'result',
149 mutation,
150 {
151 client: testClient,
152 meta: undefined,
153 mutationKey: key,
154 },
155 )
156 })
157β
158 test('should be awaited', async () => {
159 const key = queryKey()
160 const states: Array<number> = []
161 const onSuccess = () =>
162 sleep(10).then(() => {
163 states.push(1)
164 states.push(2)
165 })
166 const onSettled = () =>
167 sleep(10).then(() => {
168 states.push(5)
169 states.push(6)
170 })
171 const testCache = new MutationCache({ onSuccess, onSettled })
172 const testClient = new QueryClient({ mutationCache: testCache })
173β
174 executeMutation(
175 testClient,
176 {
177 mutationKey: key,
178 mutationFn: () => sleep(10).then(() => ({ data: 5 })),
179 onSuccess: () =>
180 sleep(10).then(() => {
181 states.push(3)
182 states.push(4)
183 }),
184 onSettled: () =>
185 sleep(10).then(() => {
186 states.push(7)
187 states.push(8)
188 }),
189 },
190 'vars',
191 )
192 await vi.advanceTimersByTimeAsync(50)
193β
194 expect(states).toEqual([1, 2, 3, 4, 5, 6, 7, 8])
195 })
196 })
197β
198 describe('MutationCacheConfig.onMutate', () => {
199 test('should be called before a mutation executes', () => {
200 const key = queryKey()
201 const onMutate = vi.fn()
202 const testCache = new MutationCache({ onMutate })
203 const testClient = new QueryClient({ mutationCache: testCache })
204β
205 executeMutation(
206 testClient,
207 {
208 mutationKey: key,
209 mutationFn: () => sleep(10).then(() => ({ data: 5 })),
210 onMutate: () => 'result',
211 },
212 'vars',
213 )
214β
215 const mutation = testCache.getAll()[0]
216β
217 expect(onMutate).toHaveBeenCalledWith('vars', mutation, {
218 client: testClient,
219 meta: undefined,
220 mutationKey: key,
221 })
222 })
223β
224 test('should be awaited', async () => {
225 const key = queryKey()
226 const states: Array<number> = []
227 const onMutate = () =>
228 sleep(10).then(() => {
229 states.push(1)
230 states.push(2)
231 })
232 const testCache = new MutationCache({ onMutate })
233 const testClient = new QueryClient({ mutationCache: testCache })
234β
235 executeMutation(
236 testClient,
237 {
238 mutationKey: key,
239 mutationFn: () => sleep(10).then(() => ({ data: 5 })),
240 onMutate: () =>
241 sleep(10).then(() => {
242 states.push(3)
243 states.push(4)
244 }),
245 },
246 'vars',
247 )
248 await vi.advanceTimersByTimeAsync(20)
249β
250 expect(states).toEqual([1, 2, 3, 4])
251 })
252β
253 test('options.onMutate should run synchronously when mutationCache.config.onMutate is not defined', () => {
254 const key = queryKey()
255 const states: Array<string> = []
256β
257 // No onMutate in cache config
258 const testCache = new MutationCache({})
259 const testClient = new QueryClient({ mutationCache: testCache })
260β
261 executeMutation(
262 testClient,
263 {
264 mutationKey: key,
265 mutationFn: () => sleep(10).then(() => ({ data: 5 })),
266 onMutate: () => {
267 states.push('onMutate')
268 return 'context'
269 },
270 },
271 'vars',
272 )
273β
274 expect(states).toEqual(['onMutate'])
275 })
276 })
277β
278 describe('find', () => {
279 test('should filter correctly', () => {
280 const testCache = new MutationCache()
281 const testClient = new QueryClient({ mutationCache: testCache })
282 const key = ['mutation', 'vars']
283β
284 executeMutation(
285 testClient,
286 {
287 mutationKey: key,
288 mutationFn: () => sleep(10).then(() => undefined),
289 },
290 'vars',
291 )
292β
293 const [mutation] = testCache.getAll()
294β
295 expect(testCache.find({ mutationKey: key })).toEqual(mutation)
296 expect(
297 testCache.find({ mutationKey: ['mutation'], exact: false }),
298 ).toEqual(mutation)
299 expect(testCache.find({ mutationKey: ['unknown'] })).toEqual(undefined)
300 expect(
301 testCache.find({
302 predicate: (m) => m.options.mutationKey?.[0] === key[0],
303 }),
304 ).toEqual(mutation)
305 })
306 })
307β
308 describe('findAll', () => {
309 test('should filter correctly', () => {
310 const testCache = new MutationCache()
311 const testClient = new QueryClient({ mutationCache: testCache })
312β
313 executeMutation(
314 testClient,
315 {
316 mutationKey: ['a', 1],
317 mutationFn: () => sleep(10).then(() => undefined),
318 },
319 1,
320 )
321 executeMutation(
322 testClient,
323 {
324 mutationKey: ['a', 2],
325 mutationFn: () => sleep(10).then(() => undefined),
326 },
327 2,
328 )
329 executeMutation(
330 testClient,
331 {
332 mutationKey: ['b'],
333 mutationFn: () => sleep(10).then(() => undefined),
334 },
335 3,
336 )
337β
338 const [mutation1, mutation2] = testCache.getAll()
339β
340 expect(
341 testCache.findAll({ mutationKey: ['a'], exact: false }),
342 ).toHaveLength(2)
343 expect(testCache.find({ mutationKey: ['a', 1] })).toEqual(mutation1)
344 expect(
345 testCache.findAll({
346 predicate: (m) => m.options.mutationKey?.[1] === 2,
347 }),
348 ).toEqual([mutation2])
349 expect(testCache.findAll({ mutationKey: ['unknown'] })).toEqual([])
350 })
351 })
352β
353 describe('garbage collection', () => {
354 test('should remove unused mutations after gcTime has elapsed', async () => {
355 const testCache = new MutationCache()
356 const testClient = new QueryClient({ mutationCache: testCache })
357 const onSuccess = vi.fn()
358β
359 executeMutation(
360 testClient,
361 {
362 mutationKey: ['a', 1],
363 gcTime: 10,
364 mutationFn: () => sleep(10).then(() => undefined),
365 onSuccess,
366 },
367 1,
368 )
369 await vi.advanceTimersByTimeAsync(10)
370β
371 expect(testCache.getAll()).toHaveLength(1)
372β
373 await vi.advanceTimersByTimeAsync(10)
374 expect(testCache.getAll()).toHaveLength(0)
375 expect(onSuccess).toHaveBeenCalledTimes(1)
376 })
377β
378 test('should not remove mutations if there are active observers', async () => {
379 const queryClient = new QueryClient()
380 const observer = new MutationObserver(queryClient, {
381 gcTime: 10,
382 mutationFn: (input: number) => sleep(10).then(() => input),
383 })
384 const unsubscribe = observer.subscribe(() => undefined)
385β
386 expect(queryClient.getMutationCache().getAll()).toHaveLength(0)
387β
388 observer.mutate(1)
389β
390 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
391β
392 await vi.advanceTimersByTimeAsync(10)
393 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
394β
395 unsubscribe()
396β
397 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
398β
399 await vi.advanceTimersByTimeAsync(10)
400 expect(queryClient.getMutationCache().getAll()).toHaveLength(0)
401 })
402β
403 test('should be garbage collected later when unsubscribed and mutation is pending', async () => {
404 const queryClient = new QueryClient()
405 const onSuccess = vi.fn()
406 const observer = new MutationObserver(queryClient, {
407 gcTime: 10,
408 mutationFn: () => sleep(10).then(() => 'data'),
409 onSuccess,
410 })
411 const unsubscribe = observer.subscribe(() => undefined)
412β
413 observer.mutate(1)
414β
415 unsubscribe()
416β
417 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
418β
419 await vi.advanceTimersByTimeAsync(10)
420 // unsubscribe should not remove even though gcTime has elapsed b/c mutation is still pending
421 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
422β
423 await vi.advanceTimersByTimeAsync(10)
424 // should be removed after an additional gcTime wait
425 expect(queryClient.getMutationCache().getAll()).toHaveLength(0)
426 expect(onSuccess).toHaveBeenCalledTimes(1)
427 })
428β
429 test('should call callbacks even with gcTime 0 and mutation still pending', async () => {
430 const queryClient = new QueryClient()
431 const onSuccess = vi.fn()
432 const observer = new MutationObserver(queryClient, {
433 gcTime: 0,
434 mutationFn: () => sleep(10).then(() => 'data'),
435 onSuccess,
436 })
437 const unsubscribe = observer.subscribe(() => undefined)
438β
439 observer.mutate(1)
440β
441 unsubscribe()
442β
443 await vi.advanceTimersByTimeAsync(10)
444 expect(queryClient.getMutationCache().getAll()).toHaveLength(0)
445 expect(onSuccess).toHaveBeenCalledTimes(1)
446 })
447 })
448β
449 describe('remove', () => {
450 test('should remove only the target mutation from scope when multiple scoped mutations exist', () => {
451 const testCache = new MutationCache()
452 const testClient = new QueryClient({ mutationCache: testCache })
453β
454 const mutation1 = testCache.build(testClient, {
455 scope: { id: 'scope1' },
456 mutationFn: () => Promise.resolve('data1'),
457 })
458 const mutation2 = testCache.build(testClient, {
459 scope: { id: 'scope1' },
460 mutationFn: () => Promise.resolve('data2'),
461 })
462β
463 expect(testCache.getAll()).toHaveLength(2)
464β
465 testCache.remove(mutation1)
466β
467 expect(testCache.getAll()).toHaveLength(1)
468 expect(testCache.getAll()).toEqual([mutation2])
469 })
470β
471 test('should delete scope when removing the only mutation in that scope', () => {
472 const testCache = new MutationCache()
473 const testClient = new QueryClient({ mutationCache: testCache })
474β
475 const mutation = testCache.build(testClient, {
476 scope: { id: 'scope1' },
477 mutationFn: () => Promise.resolve('data'),
478 })
479β
480 expect(testCache.getAll()).toHaveLength(1)
481β
482 testCache.remove(mutation)
483β
484 expect(testCache.getAll()).toHaveLength(0)
485 })
486 })
487})