Open History to see the last commit
1import { createKey, sleep } from '@tanstack/query-test-utils'
2import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
3import { MutationCache, MutationObserver, QueryClient } from '..'
4import { executeMutation } from './utils'
5import type {
6 DefaultError,
7 Mutation,
8 MutationCacheNotifyEvent,
9 MutationFunctionContext,
10} from '..'
11β
12describe('mutationCache', () => {
13 beforeEach(() => {
14 vi.useFakeTimers()
15 })
16β
17 afterEach(() => {
18 vi.useRealTimers()
19 })
20β
21 describe('MutationCacheConfig error callbacks', () => {
22 it('should call onError and onSettled when a mutation errors', async () => {
23 const key = createKey()
24 const onError =
25 vi.fn<
26 (
27 error: DefaultError,
28 variables: unknown,
29 onMutateResult: unknown,
30 mutation: Mutation<unknown, unknown, unknown>,
31 context: MutationFunctionContext,
32 ) => void
33 >()
34 const onSuccess =
35 vi.fn<
36 (
37 data: unknown,
38 variables: unknown,
39 onMutateResult: unknown,
40 mutation: Mutation<unknown, unknown, unknown>,
41 context: MutationFunctionContext,
42 ) => void
43 >()
44 const onSettled =
45 vi.fn<
46 (
47 data: unknown | undefined,
48 error: DefaultError | null,
49 variables: unknown,
50 onMutateResult: unknown,
51 mutation: Mutation<unknown, unknown, unknown>,
52 context: MutationFunctionContext,
53 ) => void
54 >()
55 const testCache = new MutationCache({ onError, onSuccess, onSettled })
56 const testClient = new QueryClient({ mutationCache: testCache })
57β
58 executeMutation(
59 testClient,
60 {
61 mutationKey: key,
62 mutationFn: () =>
63 sleep(10).then(() => Promise.reject(new Error('error'))),
64 onMutate: () => 'result',
65 },
66 'vars',
67 ).catch(() => undefined)
68 await vi.advanceTimersByTimeAsync(10)
69β
70 const mutation = testCache.getAll()[0]
71β
72 expect(onError).toHaveBeenCalledTimes(1)
73 expect(onError).toHaveBeenCalledWith(
74 new Error('error'),
75 'vars',
76 'result',
77 mutation,
78 {
79 client: testClient,
80 meta: undefined,
81 mutationKey: key,
82 },
83 )
84 expect(onSuccess).not.toHaveBeenCalled()
85 expect(onSettled).toHaveBeenCalledTimes(1)
86 expect(onSettled).toHaveBeenCalledWith(
87 undefined,
88 new Error('error'),
89 'vars',
90 'result',
91 mutation,
92 {
93 client: testClient,
94 meta: undefined,
95 mutationKey: key,
96 },
97 )
98 })
99β
100 it('should be awaited', async () => {
101 const key = createKey()
102 const states: Array<number> = []
103 const onError = () =>
104 sleep(10).then(() => {
105 states.push(1)
106 states.push(2)
107 })
108 const onSettled = () =>
109 sleep(10).then(() => {
110 states.push(5)
111 states.push(6)
112 })
113β
114 const testCache = new MutationCache({ onError, onSettled })
115 const testClient = new QueryClient({ mutationCache: testCache })
116β
117 executeMutation(
118 testClient,
119 {
120 mutationKey: key,
121 mutationFn: () =>
122 sleep(10).then(() => Promise.reject(new Error('error'))),
123 onError: () =>
124 sleep(10).then(() => {
125 states.push(3)
126 states.push(4)
127 }),
128 onSettled: () =>
129 sleep(10).then(() => {
130 states.push(7)
131 states.push(8)
132 }),
133 },
134 'vars',
135 ).catch(() => undefined)
136 await vi.advanceTimersByTimeAsync(50)
137 expect(states).toStrictEqual([1, 2, 3, 4, 5, 6, 7, 8])
138 })
139 })
140β
141 describe('MutationCacheConfig success callbacks', () => {
142 it('should call onSuccess and onSettled when a mutation is successful', async () => {
143 const key = createKey()
144 const onError =
145 vi.fn<
146 (
147 error: DefaultError,
148 variables: unknown,
149 onMutateResult: unknown,
150 mutation: Mutation<unknown, unknown, unknown>,
151 context: MutationFunctionContext,
152 ) => void
153 >()
154 const onSuccess =
155 vi.fn<
156 (
157 data: unknown,
158 variables: unknown,
159 onMutateResult: unknown,
160 mutation: Mutation<unknown, unknown, unknown>,
161 context: MutationFunctionContext,
162 ) => void
163 >()
164 const onSettled =
165 vi.fn<
166 (
167 data: unknown | undefined,
168 error: DefaultError | null,
169 variables: unknown,
170 onMutateResult: unknown,
171 mutation: Mutation<unknown, unknown, unknown>,
172 context: MutationFunctionContext,
173 ) => void
174 >()
175 const testCache = new MutationCache({ onError, onSuccess, onSettled })
176 const testClient = new QueryClient({ mutationCache: testCache })
177β
178 executeMutation(
179 testClient,
180 {
181 mutationKey: key,
182 mutationFn: () => sleep(10).then(() => ({ data: 5 })),
183 onMutate: () => 'result',
184 },
185 'vars',
186 )
187 await vi.advanceTimersByTimeAsync(10)
188β
189 const mutation = testCache.getAll()[0]
190β
191 expect(onSuccess).toHaveBeenCalledTimes(1)
192 expect(onSuccess).toHaveBeenCalledWith(
193 { data: 5 },
194 'vars',
195 'result',
196 mutation,
197 {
198 client: testClient,
199 meta: undefined,
200 mutationKey: key,
201 },
202 )
203 expect(onError).not.toHaveBeenCalled()
204 expect(onSettled).toHaveBeenCalledTimes(1)
205 expect(onSettled).toHaveBeenCalledWith(
206 { data: 5 },
207 null,
208 'vars',
209 'result',
210 mutation,
211 {
212 client: testClient,
213 meta: undefined,
214 mutationKey: key,
215 },
216 )
217 })
218β
219 it('should be awaited', async () => {
220 const key = createKey()
221 const states: Array<number> = []
222 const onSuccess = () =>
223 sleep(10).then(() => {
224 states.push(1)
225 states.push(2)
226 })
227 const onSettled = () =>
228 sleep(10).then(() => {
229 states.push(5)
230 states.push(6)
231 })
232 const testCache = new MutationCache({ onSuccess, onSettled })
233 const testClient = new QueryClient({ mutationCache: testCache })
234β
235 executeMutation(
236 testClient,
237 {
238 mutationKey: key,
239 mutationFn: () => sleep(10).then(() => ({ data: 5 })),
240 onSuccess: () =>
241 sleep(10).then(() => {
242 states.push(3)
243 states.push(4)
244 }),
245 onSettled: () =>
246 sleep(10).then(() => {
247 states.push(7)
248 states.push(8)
249 }),
250 },
251 'vars',
252 )
253 await vi.advanceTimersByTimeAsync(50)
254 expect(states).toStrictEqual([1, 2, 3, 4, 5, 6, 7, 8])
255 })
256 })
257β
258 describe('MutationCacheConfig.onMutate', () => {
259 it('should be called before a mutation executes', () => {
260 const key = createKey()
261 const onMutate =
262 vi.fn<
263 (
264 variables: unknown,
265 mutation: Mutation<unknown, unknown, unknown>,
266 context: MutationFunctionContext,
267 ) => void
268 >()
269 const testCache = new MutationCache({ onMutate })
270 const testClient = new QueryClient({ mutationCache: testCache })
271β
272 executeMutation(
273 testClient,
274 {
275 mutationKey: key,
276 mutationFn: () => sleep(10).then(() => ({ data: 5 })),
277 onMutate: () => 'result',
278 },
279 'vars',
280 )
281β
282 const mutation = testCache.getAll()[0]
283β
284 expect(onMutate).toHaveBeenCalledWith('vars', mutation, {
285 client: testClient,
286 meta: undefined,
287 mutationKey: key,
288 })
289 })
290β
291 it('should be awaited', async () => {
292 const key = createKey()
293 const states: Array<number> = []
294 const onMutate = () =>
295 sleep(10).then(() => {
296 states.push(1)
297 states.push(2)
298 })
299 const testCache = new MutationCache({ onMutate })
300 const testClient = new QueryClient({ mutationCache: testCache })
301β
302 executeMutation(
303 testClient,
304 {
305 mutationKey: key,
306 mutationFn: () => sleep(10).then(() => ({ data: 5 })),
307 onMutate: () =>
308 sleep(10).then(() => {
309 states.push(3)
310 states.push(4)
311 }),
312 },
313 'vars',
314 )
315 await vi.advanceTimersByTimeAsync(20)
316 expect(states).toStrictEqual([1, 2, 3, 4])
317 })
318β
319 it('should run options.onMutate synchronously when mutationCache.config.onMutate is not defined', () => {
320 const key = createKey()
321 const states: Array<string> = []
322β
323 // No onMutate in cache config
324 const testCache = new MutationCache({})
325 const testClient = new QueryClient({ mutationCache: testCache })
326β
327 executeMutation(
328 testClient,
329 {
330 mutationKey: key,
331 mutationFn: () => sleep(10).then(() => ({ data: 5 })),
332 onMutate: () => {
333 states.push('onMutate')
334 return 'context'
335 },
336 },
337 'vars',
338 )
339 expect(states).toStrictEqual(['onMutate'])
340 })
341 })
342β
343 describe('find', () => {
344 it('should filter correctly', () => {
345 const testCache = new MutationCache()
346 const testClient = new QueryClient({ mutationCache: testCache })
347 const key = ['mutation', 'vars']
348β
349 executeMutation(
350 testClient,
351 {
352 mutationKey: key,
353 mutationFn: () => sleep(10).then(() => undefined),
354 },
355 'vars',
356 )
357β
358 const [mutation] = testCache.getAll()
359β
360 expect(testCache.find({ mutationKey: key })).toStrictEqual(mutation)
361 expect(
362 testCache.find({ mutationKey: ['mutation'], exact: false }),
363 ).toStrictEqual(mutation)
364 expect(testCache.find({ mutationKey: ['unknown'] })).toBeUndefined()
365 expect(
366 testCache.find({
367 predicate: (m) => m.options.mutationKey?.[0] === key[0],
368 }),
369 ).toStrictEqual(mutation)
370 })
371 })
372β
373 describe('findAll', () => {
374 it('should filter correctly', () => {
375 const testCache = new MutationCache()
376 const testClient = new QueryClient({ mutationCache: testCache })
377β
378 executeMutation(
379 testClient,
380 {
381 mutationKey: ['a', 1],
382 mutationFn: () => sleep(10).then(() => undefined),
383 },
384 1,
385 )
386 executeMutation(
387 testClient,
388 {
389 mutationKey: ['a', 2],
390 mutationFn: () => sleep(10).then(() => undefined),
391 },
392 2,
393 )
394 executeMutation(
395 testClient,
396 {
397 mutationKey: ['b'],
398 mutationFn: () => sleep(10).then(() => undefined),
399 },
400 3,
401 )
402β
403 const [mutation1, mutation2] = testCache.getAll()
404β
405 expect(
406 testCache.findAll({ mutationKey: ['a'], exact: false }),
407 ).toHaveLength(2)
408 expect(testCache.find({ mutationKey: ['a', 1] })).toStrictEqual(mutation1)
409 expect(
410 testCache.findAll({
411 predicate: (m) => m.options.mutationKey?.[1] === 2,
412 }),
413 ).toStrictEqual([mutation2])
414 expect(testCache.findAll({ mutationKey: ['unknown'] })).toStrictEqual([])
415 })
416 })
417β
418 describe('garbage collection', () => {
419 it('should remove unused mutations after gcTime has elapsed', async () => {
420 const testCache = new MutationCache()
421 const testClient = new QueryClient({ mutationCache: testCache })
422 const onSuccess =
423 vi.fn<
424 (
425 data: undefined,
426 variables: number,
427 onMutateResult: unknown,
428 context: MutationFunctionContext,
429 ) => void
430 >()
431β
432 executeMutation(
433 testClient,
434 {
435 mutationKey: ['a', 1],
436 gcTime: 10,
437 mutationFn: () => sleep(10).then(() => undefined),
438 onSuccess,
439 },
440 1,
441 )
442 await vi.advanceTimersByTimeAsync(10)
443 expect(testCache.getAll()).toHaveLength(1)
444 await vi.advanceTimersByTimeAsync(10)
445 expect(testCache.getAll()).toHaveLength(0)
446 expect(onSuccess).toHaveBeenCalledTimes(1)
447 })
448β
449 it('should not remove mutations if there are active observers', async () => {
450 const queryClient = new QueryClient()
451 const observer = new MutationObserver(queryClient, {
452 gcTime: 10,
453 mutationFn: (input: number) => sleep(10).then(() => input),
454 })
455 const unsubscribe = observer.subscribe(() => undefined)
456 expect(queryClient.getMutationCache().getAll()).toHaveLength(0)
457β
458 observer.mutate(1)
459 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
460 await vi.advanceTimersByTimeAsync(10)
461 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
462β
463 unsubscribe()
464 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
465 await vi.advanceTimersByTimeAsync(10)
466 expect(queryClient.getMutationCache().getAll()).toHaveLength(0)
467 })
468β
469 it('should be garbage collected later when unsubscribed and mutation is pending', async () => {
470 const queryClient = new QueryClient()
471 const onSuccess =
472 vi.fn<
473 (
474 data: string,
475 variables: number,
476 onMutateResult: unknown,
477 context: MutationFunctionContext,
478 ) => void
479 >()
480 const observer = new MutationObserver(queryClient, {
481 gcTime: 10,
482 mutationFn: () => sleep(10).then(() => 'data'),
483 onSuccess,
484 })
485 const unsubscribe = observer.subscribe(() => undefined)
486β
487 observer.mutate(1)
488β
489 unsubscribe()
490 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
491 await vi.advanceTimersByTimeAsync(10)
492 // unsubscribe should not remove even though gcTime has elapsed b/c mutation is still pending
493 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
494 await vi.advanceTimersByTimeAsync(10)
495 // should be removed after an additional gcTime wait
496 expect(queryClient.getMutationCache().getAll()).toHaveLength(0)
497 expect(onSuccess).toHaveBeenCalledTimes(1)
498 })
499β
500 it('should call callbacks even with gcTime 0 and mutation still pending', async () => {
501 const queryClient = new QueryClient()
502 const onSuccess =
503 vi.fn<
504 (
505 data: string,
506 variables: number,
507 onMutateResult: unknown,
508 context: MutationFunctionContext,
509 ) => void
510 >()
511 const observer = new MutationObserver(queryClient, {
512 gcTime: 0,
513 mutationFn: () => sleep(10).then(() => 'data'),
514 onSuccess,
515 })
516 const unsubscribe = observer.subscribe(() => undefined)
517β
518 observer.mutate(1)
519β
520 unsubscribe()
521 await vi.advanceTimersByTimeAsync(10)
522 expect(queryClient.getMutationCache().getAll()).toHaveLength(0)
523 expect(onSuccess).toHaveBeenCalledTimes(1)
524 })
525 })
526β
527 describe('clear', () => {
528 it('should notify subscribers after all mutations have been removed', () => {
529 const testCache = new MutationCache()
530 const testClient = new QueryClient({ mutationCache: testCache })
531 const mutation1 = testCache.build(testClient, {})
532 const mutation2 = testCache.build(testClient, {})
533 const callback = vi.fn<
534 () => Array<Mutation<unknown, Error, unknown, unknown>>
535 >(() => testCache.getAll())
536 testCache.subscribe(callback)
537β
538 testCache.clear()
539β
540 expect(callback).toHaveBeenCalledTimes(2)
541 expect(callback).toHaveBeenNthCalledWith(1, {
542 type: 'removed',
543 mutation: mutation1,
544 })
545 expect(callback).toHaveBeenNthCalledWith(2, {
546 type: 'removed',
547 mutation: mutation2,
548 })
549 expect(callback).toHaveNthReturnedWith(1, [])
550 expect(callback).toHaveNthReturnedWith(2, [])
551 expect(testCache.getAll()).toStrictEqual([])
552 })
553β
554 it('should preserve mutations added by removal subscribers', () => {
555 const testCache = new MutationCache()
556 const testClient = new QueryClient({ mutationCache: testCache })
557 const original = testCache.build(testClient, {})
558 const key = createKey()
559 testCache.subscribe((event) => {
560 if (event.type === 'removed' && event.mutation === original) {
561 testCache.build(testClient, { mutationKey: key })
562 }
563 })
564β
565 testCache.clear()
566β
567 expect(testCache.getAll()).toHaveLength(1)
568 expect(testCache.getAll()[0]?.options.mutationKey).toStrictEqual(key)
569 })
570 })
571β
572 describe('remove', () => {
573 it('should remove only the target mutation from scope when multiple scoped mutations exist', () => {
574 const testCache = new MutationCache()
575 const testClient = new QueryClient({ mutationCache: testCache })
576β
577 const mutation1 = testCache.build(testClient, {
578 scope: { id: 'scope1' },
579 mutationFn: () => Promise.resolve('data1'),
580 })
581 const mutation2 = testCache.build(testClient, {
582 scope: { id: 'scope1' },
583 mutationFn: () => Promise.resolve('data2'),
584 })
585β
586 expect(testCache.getAll()).toHaveLength(2)
587β
588 testCache.remove(mutation1)
589β
590 expect(testCache.getAll()).toHaveLength(1)
591 expect(testCache.getAll()).toStrictEqual([mutation2])
592 })
593β
594 it('should delete scope when removing the only mutation in that scope', () => {
595 const testCache = new MutationCache()
596 const testClient = new QueryClient({ mutationCache: testCache })
597β
598 const mutation = testCache.build(testClient, {
599 scope: { id: 'scope1' },
600 mutationFn: () => Promise.resolve('data'),
601 })
602β
603 expect(testCache.getAll()).toHaveLength(1)
604β
605 testCache.remove(mutation)
606β
607 expect(testCache.getAll()).toHaveLength(0)
608 })
609β
610 it('should still notify removal when removing a mutation that does not exist in the cache', () => {
611 const testCache = new MutationCache()
612 const testClient = new QueryClient({ mutationCache: testCache })
613β
614 const mutation = testCache.build(testClient, {
615 mutationFn: () => Promise.resolve('data'),
616 })
617β
618 expect(testCache.getAll()).toHaveLength(1)
619 testCache.remove(mutation)
620 expect(testCache.getAll()).toHaveLength(0)
621β
622 // Remove again β mutation is already gone from the cache
623 const callback = vi.fn<(event: MutationCacheNotifyEvent) => void>()
624 const unsubscribe = testCache.subscribe(callback)
625 testCache.remove(mutation)
626β
627 expect(testCache.getAll()).toHaveLength(0)
628 expect(callback).toHaveBeenCalledTimes(1)
629 expect(callback).toHaveBeenCalledWith({ type: 'removed', mutation })
630β
631 unsubscribe()
632 })
633 })
634})