Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, it, 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 it('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 it('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 expect(states).toEqual([1, 2, 3, 4, 5, 6, 7, 8])
104 })
105 })
106β
107 describe('MutationCacheConfig success callbacks', () => {
108 it('should call onSuccess and onSettled when a mutation is successful', async () => {
109 const key = queryKey()
110 const onError = vi.fn()
111 const onSuccess = vi.fn()
112 const onSettled = vi.fn()
113 const testCache = new MutationCache({ onError, onSuccess, onSettled })
114 const testClient = new QueryClient({ mutationCache: testCache })
115β
116 executeMutation(
117 testClient,
118 {
119 mutationKey: key,
120 mutationFn: () => sleep(10).then(() => ({ data: 5 })),
121 onMutate: () => 'result',
122 },
123 'vars',
124 )
125 await vi.advanceTimersByTimeAsync(10)
126β
127 const mutation = testCache.getAll()[0]
128β
129 expect(onSuccess).toHaveBeenCalledTimes(1)
130 expect(onSuccess).toHaveBeenCalledWith(
131 { data: 5 },
132 'vars',
133 'result',
134 mutation,
135 {
136 client: testClient,
137 meta: undefined,
138 mutationKey: key,
139 },
140 )
141 expect(onError).not.toHaveBeenCalled()
142 expect(onSettled).toHaveBeenCalledTimes(1)
143 expect(onSettled).toHaveBeenCalledWith(
144 { data: 5 },
145 null,
146 'vars',
147 'result',
148 mutation,
149 {
150 client: testClient,
151 meta: undefined,
152 mutationKey: key,
153 },
154 )
155 })
156β
157 it('should be awaited', async () => {
158 const key = queryKey()
159 const states: Array<number> = []
160 const onSuccess = () =>
161 sleep(10).then(() => {
162 states.push(1)
163 states.push(2)
164 })
165 const onSettled = () =>
166 sleep(10).then(() => {
167 states.push(5)
168 states.push(6)
169 })
170 const testCache = new MutationCache({ onSuccess, onSettled })
171 const testClient = new QueryClient({ mutationCache: testCache })
172β
173 executeMutation(
174 testClient,
175 {
176 mutationKey: key,
177 mutationFn: () => sleep(10).then(() => ({ data: 5 })),
178 onSuccess: () =>
179 sleep(10).then(() => {
180 states.push(3)
181 states.push(4)
182 }),
183 onSettled: () =>
184 sleep(10).then(() => {
185 states.push(7)
186 states.push(8)
187 }),
188 },
189 'vars',
190 )
191 await vi.advanceTimersByTimeAsync(50)
192 expect(states).toEqual([1, 2, 3, 4, 5, 6, 7, 8])
193 })
194 })
195β
196 describe('MutationCacheConfig.onMutate', () => {
197 it('should be called before a mutation executes', () => {
198 const key = queryKey()
199 const onMutate = vi.fn()
200 const testCache = new MutationCache({ onMutate })
201 const testClient = new QueryClient({ mutationCache: testCache })
202β
203 executeMutation(
204 testClient,
205 {
206 mutationKey: key,
207 mutationFn: () => sleep(10).then(() => ({ data: 5 })),
208 onMutate: () => 'result',
209 },
210 'vars',
211 )
212β
213 const mutation = testCache.getAll()[0]
214β
215 expect(onMutate).toHaveBeenCalledWith('vars', mutation, {
216 client: testClient,
217 meta: undefined,
218 mutationKey: key,
219 })
220 })
221β
222 it('should be awaited', async () => {
223 const key = queryKey()
224 const states: Array<number> = []
225 const onMutate = () =>
226 sleep(10).then(() => {
227 states.push(1)
228 states.push(2)
229 })
230 const testCache = new MutationCache({ onMutate })
231 const testClient = new QueryClient({ mutationCache: testCache })
232β
233 executeMutation(
234 testClient,
235 {
236 mutationKey: key,
237 mutationFn: () => sleep(10).then(() => ({ data: 5 })),
238 onMutate: () =>
239 sleep(10).then(() => {
240 states.push(3)
241 states.push(4)
242 }),
243 },
244 'vars',
245 )
246 await vi.advanceTimersByTimeAsync(20)
247 expect(states).toEqual([1, 2, 3, 4])
248 })
249β
250 it('should run options.onMutate synchronously when mutationCache.config.onMutate is not defined', () => {
251 const key = queryKey()
252 const states: Array<string> = []
253β
254 // No onMutate in cache config
255 const testCache = new MutationCache({})
256 const testClient = new QueryClient({ mutationCache: testCache })
257β
258 executeMutation(
259 testClient,
260 {
261 mutationKey: key,
262 mutationFn: () => sleep(10).then(() => ({ data: 5 })),
263 onMutate: () => {
264 states.push('onMutate')
265 return 'context'
266 },
267 },
268 'vars',
269 )
270 expect(states).toEqual(['onMutate'])
271 })
272 })
273β
274 describe('find', () => {
275 it('should filter correctly', () => {
276 const testCache = new MutationCache()
277 const testClient = new QueryClient({ mutationCache: testCache })
278 const key = ['mutation', 'vars']
279β
280 executeMutation(
281 testClient,
282 {
283 mutationKey: key,
284 mutationFn: () => sleep(10).then(() => undefined),
285 },
286 'vars',
287 )
288β
289 const [mutation] = testCache.getAll()
290β
291 expect(testCache.find({ mutationKey: key })).toEqual(mutation)
292 expect(
293 testCache.find({ mutationKey: ['mutation'], exact: false }),
294 ).toEqual(mutation)
295 expect(testCache.find({ mutationKey: ['unknown'] })).toEqual(undefined)
296 expect(
297 testCache.find({
298 predicate: (m) => m.options.mutationKey?.[0] === key[0],
299 }),
300 ).toEqual(mutation)
301 })
302 })
303β
304 describe('findAll', () => {
305 it('should filter correctly', () => {
306 const testCache = new MutationCache()
307 const testClient = new QueryClient({ mutationCache: testCache })
308β
309 executeMutation(
310 testClient,
311 {
312 mutationKey: ['a', 1],
313 mutationFn: () => sleep(10).then(() => undefined),
314 },
315 1,
316 )
317 executeMutation(
318 testClient,
319 {
320 mutationKey: ['a', 2],
321 mutationFn: () => sleep(10).then(() => undefined),
322 },
323 2,
324 )
325 executeMutation(
326 testClient,
327 {
328 mutationKey: ['b'],
329 mutationFn: () => sleep(10).then(() => undefined),
330 },
331 3,
332 )
333β
334 const [mutation1, mutation2] = testCache.getAll()
335β
336 expect(
337 testCache.findAll({ mutationKey: ['a'], exact: false }),
338 ).toHaveLength(2)
339 expect(testCache.find({ mutationKey: ['a', 1] })).toEqual(mutation1)
340 expect(
341 testCache.findAll({
342 predicate: (m) => m.options.mutationKey?.[1] === 2,
343 }),
344 ).toEqual([mutation2])
345 expect(testCache.findAll({ mutationKey: ['unknown'] })).toEqual([])
346 })
347 })
348β
349 describe('garbage collection', () => {
350 it('should remove unused mutations after gcTime has elapsed', async () => {
351 const testCache = new MutationCache()
352 const testClient = new QueryClient({ mutationCache: testCache })
353 const onSuccess = vi.fn()
354β
355 executeMutation(
356 testClient,
357 {
358 mutationKey: ['a', 1],
359 gcTime: 10,
360 mutationFn: () => sleep(10).then(() => undefined),
361 onSuccess,
362 },
363 1,
364 )
365 await vi.advanceTimersByTimeAsync(10)
366 expect(testCache.getAll()).toHaveLength(1)
367 await vi.advanceTimersByTimeAsync(10)
368 expect(testCache.getAll()).toHaveLength(0)
369 expect(onSuccess).toHaveBeenCalledTimes(1)
370 })
371β
372 it('should not remove mutations if there are active observers', async () => {
373 const queryClient = new QueryClient()
374 const observer = new MutationObserver(queryClient, {
375 gcTime: 10,
376 mutationFn: (input: number) => sleep(10).then(() => input),
377 })
378 const unsubscribe = observer.subscribe(() => undefined)
379 expect(queryClient.getMutationCache().getAll()).toHaveLength(0)
380β
381 observer.mutate(1)
382 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
383 await vi.advanceTimersByTimeAsync(10)
384 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
385β
386 unsubscribe()
387 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
388 await vi.advanceTimersByTimeAsync(10)
389 expect(queryClient.getMutationCache().getAll()).toHaveLength(0)
390 })
391β
392 it('should be garbage collected later when unsubscribed and mutation is pending', async () => {
393 const queryClient = new QueryClient()
394 const onSuccess = vi.fn()
395 const observer = new MutationObserver(queryClient, {
396 gcTime: 10,
397 mutationFn: () => sleep(10).then(() => 'data'),
398 onSuccess,
399 })
400 const unsubscribe = observer.subscribe(() => undefined)
401β
402 observer.mutate(1)
403β
404 unsubscribe()
405 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
406 await vi.advanceTimersByTimeAsync(10)
407 // unsubscribe should not remove even though gcTime has elapsed b/c mutation is still pending
408 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
409 await vi.advanceTimersByTimeAsync(10)
410 // should be removed after an additional gcTime wait
411 expect(queryClient.getMutationCache().getAll()).toHaveLength(0)
412 expect(onSuccess).toHaveBeenCalledTimes(1)
413 })
414β
415 it('should call callbacks even with gcTime 0 and mutation still pending', async () => {
416 const queryClient = new QueryClient()
417 const onSuccess = vi.fn()
418 const observer = new MutationObserver(queryClient, {
419 gcTime: 0,
420 mutationFn: () => sleep(10).then(() => 'data'),
421 onSuccess,
422 })
423 const unsubscribe = observer.subscribe(() => undefined)
424β
425 observer.mutate(1)
426β
427 unsubscribe()
428 await vi.advanceTimersByTimeAsync(10)
429 expect(queryClient.getMutationCache().getAll()).toHaveLength(0)
430 expect(onSuccess).toHaveBeenCalledTimes(1)
431 })
432 })
433β
434 describe('clear', () => {
435 it('should notify subscribers after all mutations have been removed', () => {
436 const testCache = new MutationCache()
437 const testClient = new QueryClient({ mutationCache: testCache })
438 const mutation1 = testCache.build(testClient, {})
439 const mutation2 = testCache.build(testClient, {})
440 const callback = vi.fn(() => testCache.getAll())
441 testCache.subscribe(callback)
442β
443 testCache.clear()
444β
445 expect(callback).toHaveBeenCalledTimes(2)
446 expect(callback).toHaveBeenNthCalledWith(1, {
447 type: 'removed',
448 mutation: mutation1,
449 })
450 expect(callback).toHaveBeenNthCalledWith(2, {
451 type: 'removed',
452 mutation: mutation2,
453 })
454 expect(callback).toHaveNthReturnedWith(1, [])
455 expect(callback).toHaveNthReturnedWith(2, [])
456 expect(testCache.getAll()).toEqual([])
457 })
458β
459 it('should preserve mutations added by removal subscribers', () => {
460 const testCache = new MutationCache()
461 const testClient = new QueryClient({ mutationCache: testCache })
462 const original = testCache.build(testClient, {})
463 const key = queryKey()
464 testCache.subscribe((event) => {
465 if (event.type === 'removed' && event.mutation === original) {
466 testCache.build(testClient, { mutationKey: key })
467 }
468 })
469β
470 testCache.clear()
471β
472 expect(testCache.getAll()).toHaveLength(1)
473 expect(testCache.getAll()[0]?.options.mutationKey).toEqual(key)
474 })
475 })
476β
477 describe('remove', () => {
478 it('should remove only the target mutation from scope when multiple scoped mutations exist', () => {
479 const testCache = new MutationCache()
480 const testClient = new QueryClient({ mutationCache: testCache })
481β
482 const mutation1 = testCache.build(testClient, {
483 scope: { id: 'scope1' },
484 mutationFn: () => Promise.resolve('data1'),
485 })
486 const mutation2 = testCache.build(testClient, {
487 scope: { id: 'scope1' },
488 mutationFn: () => Promise.resolve('data2'),
489 })
490β
491 expect(testCache.getAll()).toHaveLength(2)
492β
493 testCache.remove(mutation1)
494β
495 expect(testCache.getAll()).toHaveLength(1)
496 expect(testCache.getAll()).toEqual([mutation2])
497 })
498β
499 it('should delete scope when removing the only mutation in that scope', () => {
500 const testCache = new MutationCache()
501 const testClient = new QueryClient({ mutationCache: testCache })
502β
503 const mutation = testCache.build(testClient, {
504 scope: { id: 'scope1' },
505 mutationFn: () => Promise.resolve('data'),
506 })
507β
508 expect(testCache.getAll()).toHaveLength(1)
509β
510 testCache.remove(mutation)
511β
512 expect(testCache.getAll()).toHaveLength(0)
513 })
514β
515 it('should still notify removal when removing a mutation that does not exist in the cache', () => {
516 const testCache = new MutationCache()
517 const testClient = new QueryClient({ mutationCache: testCache })
518β
519 const mutation = testCache.build(testClient, {
520 mutationFn: () => Promise.resolve('data'),
521 })
522β
523 expect(testCache.getAll()).toHaveLength(1)
524 testCache.remove(mutation)
525 expect(testCache.getAll()).toHaveLength(0)
526β
527 // Remove again β mutation is already gone from the cache
528 const callback = vi.fn()
529 const unsubscribe = testCache.subscribe(callback)
530 testCache.remove(mutation)
531β
532 expect(testCache.getAll()).toHaveLength(0)
533 expect(callback).toHaveBeenCalledTimes(1)
534 expect(callback).toHaveBeenCalledWith({ type: 'removed', mutation })
535β
536 unsubscribe()
537 })
538 })
539})