Open History to see the last commit
1import { queryKey, sleep } from '@tanstack/query-test-utils'
2import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
3import { MutationCache, QueryClient, focusManager } from '..'
4import { MutationObserver } from '../mutationObserver'
5import { executeMutation } from './utils'
6import type { MutationState } from '../mutation'
7β
8describe('mutation', () => {
9 let queryClient: QueryClient
10β
11 beforeEach(() => {
12 vi.useFakeTimers()
13 queryClient = new QueryClient()
14 queryClient.mount()
15 })
16β
17 afterEach(() => {
18 queryClient.clear()
19 vi.useRealTimers()
20 })
21β
22 it('should accept null values in mutate', async () => {
23 let variables
24β
25 const mutation = new MutationObserver(queryClient, {
26 mutationFn: (vars: unknown) => {
27 variables = vars
28 return Promise.resolve(vars)
29 },
30 })
31β
32 mutation.mutate(null)
33 await vi.advanceTimersByTimeAsync(0)
34 expect(variables).toBe(null)
35 })
36β
37 it('should be able to set defaults with setMutationDefaults', async () => {
38 const key = queryKey()
39 const fn = vi.fn()
40β
41 queryClient.setMutationDefaults(key, {
42 mutationFn: fn,
43 })
44β
45 executeMutation(
46 queryClient,
47 {
48 mutationKey: key,
49 },
50 'vars',
51 )
52 await vi.advanceTimersByTimeAsync(0)
53 expect(fn).toHaveBeenCalledTimes(1)
54 expect(fn).toHaveBeenCalledWith('vars', {
55 client: queryClient,
56 meta: undefined,
57 mutationKey: key,
58 })
59 })
60β
61 it('should set correct success states on mutation', async () => {
62 const mutation = new MutationObserver(queryClient, {
63 mutationFn: (text: string) => sleep(10).then(() => text),
64 onMutate: (text) => text,
65 })
66β
67 expect(mutation.getCurrentResult()).toEqual({
68 context: undefined,
69 data: undefined,
70 error: null,
71 failureCount: 0,
72 failureReason: null,
73 isError: false,
74 isIdle: true,
75 isPending: false,
76 isPaused: false,
77 isSuccess: false,
78 mutate: expect.any(Function),
79 reset: expect.any(Function),
80 status: 'idle',
81 variables: undefined,
82 submittedAt: 0,
83 })
84β
85 const states: Array<MutationState<string, unknown, string, string>> = []
86β
87 mutation.subscribe((state) => {
88 states.push(state)
89 })
90β
91 mutation.mutate('todo')
92 await vi.advanceTimersByTimeAsync(0)
93 expect(states[0]).toEqual({
94 context: undefined,
95 data: undefined,
96 error: null,
97 failureCount: 0,
98 failureReason: null,
99 isError: false,
100 isIdle: false,
101 isPending: true,
102 isPaused: false,
103 isSuccess: false,
104 mutate: expect.any(Function),
105 reset: expect.any(Function),
106 status: 'pending',
107 variables: 'todo',
108 submittedAt: expect.any(Number),
109 })
110 await vi.advanceTimersByTimeAsync(0)
111 expect(states[1]).toEqual({
112 context: 'todo',
113 data: undefined,
114 error: null,
115 failureCount: 0,
116 failureReason: null,
117 isError: false,
118 isIdle: false,
119 isPending: true,
120 isPaused: false,
121 isSuccess: false,
122 mutate: expect.any(Function),
123 reset: expect.any(Function),
124 status: 'pending',
125 variables: 'todo',
126 submittedAt: expect.any(Number),
127 })
128 await vi.advanceTimersByTimeAsync(10)
129 expect(states[2]).toEqual({
130 context: 'todo',
131 data: 'todo',
132 error: null,
133 failureCount: 0,
134 failureReason: null,
135 isError: false,
136 isIdle: false,
137 isPending: false,
138 isPaused: false,
139 isSuccess: true,
140 mutate: expect.any(Function),
141 reset: expect.any(Function),
142 status: 'success',
143 variables: 'todo',
144 submittedAt: expect.any(Number),
145 })
146 })
147β
148 it('should set correct error states on mutation', async () => {
149 const mutation = new MutationObserver(queryClient, {
150 mutationFn: (_: string) =>
151 sleep(20).then(() => Promise.reject(new Error('err'))),
152 onMutate: (text) => text,
153 retry: 1,
154 retryDelay: 10,
155 })
156β
157 const states: Array<MutationState<string, unknown, string, string>> = []
158β
159 mutation.subscribe((state) => {
160 states.push(state)
161 })
162β
163 mutation.mutate('todo').catch(() => undefined)
164 await vi.advanceTimersByTimeAsync(0)
165 expect(states[0]).toEqual({
166 context: undefined,
167 data: undefined,
168 error: null,
169 failureCount: 0,
170 failureReason: null,
171 isError: false,
172 isIdle: false,
173 isPending: true,
174 isPaused: false,
175 isSuccess: false,
176 mutate: expect.any(Function),
177 reset: expect.any(Function),
178 status: 'pending',
179 variables: 'todo',
180 submittedAt: expect.any(Number),
181 })
182 await vi.advanceTimersByTimeAsync(0)
183 expect(states[1]).toEqual({
184 context: 'todo',
185 data: undefined,
186 error: null,
187 failureCount: 0,
188 failureReason: null,
189 isError: false,
190 isIdle: false,
191 isPending: true,
192 isPaused: false,
193 isSuccess: false,
194 mutate: expect.any(Function),
195 reset: expect.any(Function),
196 status: 'pending',
197 variables: 'todo',
198 submittedAt: expect.any(Number),
199 })
200 await vi.advanceTimersByTimeAsync(20)
201 expect(states[2]).toEqual({
202 context: 'todo',
203 data: undefined,
204 error: null,
205 failureCount: 1,
206 failureReason: new Error('err'),
207 isError: false,
208 isIdle: false,
209 isPending: true,
210 isPaused: false,
211 isSuccess: false,
212 mutate: expect.any(Function),
213 reset: expect.any(Function),
214 status: 'pending',
215 variables: 'todo',
216 submittedAt: expect.any(Number),
217 })
218 await vi.advanceTimersByTimeAsync(30)
219 expect(states[3]).toEqual({
220 context: 'todo',
221 data: undefined,
222 error: new Error('err'),
223 failureCount: 2,
224 failureReason: new Error('err'),
225 isError: true,
226 isIdle: false,
227 isPending: false,
228 isPaused: false,
229 isSuccess: false,
230 mutate: expect.any(Function),
231 reset: expect.any(Function),
232 status: 'error',
233 variables: 'todo',
234 submittedAt: expect.any(Number),
235 })
236 })
237β
238 it('should be able to restore a mutation', async () => {
239 const key = queryKey()
240β
241 const onMutate = vi.fn()
242 const onSuccess = vi.fn()
243 const onSettled = vi.fn()
244β
245 queryClient.setMutationDefaults(key, {
246 mutationFn: (text: string) => sleep(10).then(() => text),
247 onMutate,
248 onSuccess,
249 onSettled,
250 })
251β
252 const mutation = queryClient
253 .getMutationCache()
254 .build<string, unknown, string, string>(
255 queryClient,
256 {
257 mutationKey: key,
258 },
259 {
260 context: 'todo',
261 data: undefined,
262 error: null,
263 failureCount: 1,
264 failureReason: 'err',
265 isPaused: true,
266 status: 'pending',
267 variables: 'todo',
268 submittedAt: 1,
269 },
270 )
271β
272 expect(mutation.state).toEqual({
273 context: 'todo',
274 data: undefined,
275 error: null,
276 failureCount: 1,
277 failureReason: 'err',
278 isPaused: true,
279 status: 'pending',
280 variables: 'todo',
281 submittedAt: 1,
282 })
283β
284 void queryClient.resumePausedMutations()
285β
286 // check that the mutation is correctly resumed
287 expect(mutation.state).toEqual({
288 context: 'todo',
289 data: undefined,
290 error: null,
291 failureCount: 1,
292 failureReason: 'err',
293 isPaused: false,
294 status: 'pending',
295 variables: 'todo',
296 submittedAt: 1,
297 })
298 await vi.advanceTimersByTimeAsync(10)
299 expect(mutation.state).toEqual({
300 context: 'todo',
301 data: 'todo',
302 error: null,
303 failureCount: 0,
304 failureReason: null,
305 isPaused: false,
306 status: 'success',
307 variables: 'todo',
308 submittedAt: 1,
309 })
310β
311 expect(onMutate).not.toHaveBeenCalled()
312 expect(onSuccess).toHaveBeenCalled()
313 expect(onSettled).toHaveBeenCalled()
314 })
315β
316 it('should not add an existing observer with addObserver', () => {
317 const mutationCache = queryClient.getMutationCache()
318 const observer = new MutationObserver(queryClient, {})
319 const currentMutation = mutationCache.build(queryClient, {})
320β
321 const fn = vi.fn()
322β
323 const unsubscribe = mutationCache.subscribe((event) => {
324 fn(event.type)
325 })
326β
327 currentMutation.addObserver(observer)
328 currentMutation.addObserver(observer)
329β
330 expect(fn).toHaveBeenCalledTimes(1)
331 expect(fn).toHaveBeenCalledWith('observerAdded')
332β
333 unsubscribe()
334 })
335β
336 it('should throw an error from mutate if no mutationFn found', async () => {
337 const mutation = new MutationObserver(queryClient, {
338 mutationFn: undefined,
339 retry: false,
340 })
341β
342 let error: any
343 try {
344 await mutation.mutate()
345 } catch (err) {
346 error = err
347 }
348 expect(error).toEqual(new Error('No mutationFn found'))
349 })
350β
351 it('should update the mutation state with mutate even without an active subscription 1', async () => {
352 const onSuccess = vi.fn()
353 const onSettled = vi.fn()
354β
355 const mutation = new MutationObserver(queryClient, {
356 mutationFn: () => {
357 return Promise.resolve('update')
358 },
359 })
360β
361 mutation.mutate(undefined, { onSuccess, onSettled })
362 await vi.advanceTimersByTimeAsync(0)
363 expect(mutation.getCurrentResult().data).toEqual('update')
364 expect(onSuccess).not.toHaveBeenCalled()
365 expect(onSettled).not.toHaveBeenCalled()
366 })
367β
368 it('should update the mutation state with mutate even without an active subscription 2', async () => {
369 const onSuccess = vi.fn()
370 const onSettled = vi.fn()
371β
372 const mutation = new MutationObserver(queryClient, {
373 mutationFn: () => {
374 return Promise.resolve('update')
375 },
376 })
377β
378 mutation.mutate(undefined, { onSuccess, onSettled })
379 await vi.advanceTimersByTimeAsync(0)
380 expect(mutation.getCurrentResult().data).toEqual('update')
381 expect(onSuccess).not.toHaveBeenCalled()
382 expect(onSettled).not.toHaveBeenCalled()
383 })
384β
385 it('should see updated options in mutation callbacks', async () => {
386 const onSuccess = vi.fn()
387β
388 const mutation = new MutationObserver(queryClient, {
389 mutationFn: () => sleep(100).then(() => Promise.resolve('update')),
390 onSuccess: () => {
391 onSuccess(1)
392 },
393 })
394β
395 void mutation.mutate()
396β
397 mutation.setOptions({
398 mutationFn: () => sleep(100).then(() => Promise.resolve('update')),
399 onSuccess: () => {
400 onSuccess(2)
401 },
402 })
403 await vi.advanceTimersByTimeAsync(100)
404 expect(onSuccess).toHaveBeenCalledTimes(1)
405β
406 expect(onSuccess).toHaveBeenCalledWith(2)
407 })
408β
409 describe('scoped mutations', () => {
410 it('should run mutations in the same scope in serial', async () => {
411 const key1 = queryKey()
412 const key2 = queryKey()
413β
414 const results: Array<string> = []
415β
416 executeMutation(
417 queryClient,
418 {
419 mutationKey: key1,
420 scope: {
421 id: 'scope',
422 },
423 mutationFn: async () => {
424 results.push('start-A')
425 await sleep(10)
426 results.push('finish-A')
427 return 'a'
428 },
429 },
430 'vars1',
431 )
432 expect(
433 queryClient.getMutationCache().find({ mutationKey: key1 })?.state,
434 ).toMatchObject({
435 status: 'pending',
436 isPaused: false,
437 })
438β
439 executeMutation(
440 queryClient,
441 {
442 mutationKey: key2,
443 scope: {
444 id: 'scope',
445 },
446 mutationFn: async () => {
447 results.push('start-B')
448 await sleep(10)
449 results.push('finish-B')
450 return 'b'
451 },
452 },
453 'vars2',
454 )
455 expect(
456 queryClient.getMutationCache().find({ mutationKey: key2 })?.state,
457 ).toMatchObject({
458 status: 'pending',
459 isPaused: true,
460 })
461 await vi.advanceTimersByTimeAsync(20)
462 expect(results).toStrictEqual([
463 'start-A',
464 'finish-A',
465 'start-B',
466 'finish-B',
467 ])
468 })
469β
470 it('should start the next mutation in the same scope while the window is not focused', async () => {
471 const key1 = queryKey()
472 const key2 = queryKey()
473β
474 const results: Array<string> = []
475β
476 focusManager.setFocused(false)
477β
478 try {
479 executeMutation(
480 queryClient,
481 {
482 mutationKey: key1,
483 scope: {
484 id: 'scope',
485 },
486 networkMode: 'always',
487 mutationFn: async () => {
488 results.push('start-A')
489 await sleep(10)
490 results.push('finish-A')
491 return 'a'
492 },
493 },
494 'vars1',
495 )
496β
497 executeMutation(
498 queryClient,
499 {
500 mutationKey: key2,
501 scope: {
502 id: 'scope',
503 },
504 networkMode: 'always',
505 mutationFn: async () => {
506 results.push('start-B')
507 await sleep(10)
508 results.push('finish-B')
509 return 'b'
510 },
511 },
512 'vars2',
513 )
514β
515 await vi.advanceTimersByTimeAsync(20)
516 expect(results).toStrictEqual([
517 'start-A',
518 'finish-A',
519 'start-B',
520 'finish-B',
521 ])
522 expect(
523 queryClient.getMutationCache().find({ mutationKey: key2 })?.state,
524 ).toMatchObject({
525 status: 'success',
526 isPaused: false,
527 })
528 } finally {
529 focusManager.setFocused(undefined)
530 }
531 })
532 })
533β
534 it('should run mutations without scope in parallel', async () => {
535 const key1 = queryKey()
536 const key2 = queryKey()
537β
538 const results: Array<string> = []
539β
540 executeMutation(
541 queryClient,
542 {
543 mutationKey: key1,
544 mutationFn: async () => {
545 results.push('start-A')
546 await sleep(10)
547 results.push('finish-A')
548 return 'a'
549 },
550 },
551 'vars1',
552 )
553β
554 executeMutation(
555 queryClient,
556 {
557 mutationKey: key2,
558 mutationFn: async () => {
559 results.push('start-B')
560 await sleep(10)
561 results.push('finish-B')
562 return 'b'
563 },
564 },
565 'vars2',
566 )
567 await vi.advanceTimersByTimeAsync(10)
568 expect(results).toStrictEqual([
569 'start-A',
570 'start-B',
571 'finish-A',
572 'finish-B',
573 ])
574 })
575β
576 it('should run each scope in parallel, serial within scope', async () => {
577 const results: Array<string> = []
578β
579 executeMutation(
580 queryClient,
581 {
582 scope: {
583 id: '1',
584 },
585 mutationFn: async () => {
586 results.push('start-A1')
587 await sleep(10)
588 results.push('finish-A1')
589 return 'a'
590 },
591 },
592 'vars1',
593 )
594β
595 executeMutation(
596 queryClient,
597 {
598 scope: {
599 id: '1',
600 },
601 mutationFn: async () => {
602 results.push('start-B1')
603 await sleep(10)
604 results.push('finish-B1')
605 return 'b'
606 },
607 },
608 'vars2',
609 )
610β
611 executeMutation(
612 queryClient,
613 {
614 scope: {
615 id: '2',
616 },
617 mutationFn: async () => {
618 results.push('start-A2')
619 await sleep(10)
620 results.push('finish-A2')
621 return 'a'
622 },
623 },
624 'vars1',
625 )
626β
627 executeMutation(
628 queryClient,
629 {
630 scope: {
631 id: '2',
632 },
633 mutationFn: async () => {
634 results.push('start-B2')
635 await sleep(10)
636 results.push('finish-B2')
637 return 'b'
638 },
639 },
640 'vars2',
641 )
642 await vi.advanceTimersByTimeAsync(20)
643 expect(results).toStrictEqual([
644 'start-A1',
645 'start-A2',
646 'finish-A1',
647 'start-B1',
648 'finish-A2',
649 'start-B2',
650 'finish-B1',
651 'finish-B2',
652 ])
653 })
654β
655 describe('callback return types', () => {
656 it('should handle all sync callback patterns', async () => {
657 const key = queryKey()
658 const results: Array<string> = []
659β
660 executeMutation(
661 queryClient,
662 {
663 mutationKey: key,
664 mutationFn: () => Promise.resolve('success'),
665 onMutate: () => {
666 results.push('onMutate-sync')
667 return { backup: 'data' } // onMutate can return a result
668 },
669 onSuccess: () => {
670 results.push('onSuccess-implicit-void')
671 // Implicit void return
672 },
673 onError: () => {
674 results.push('onError-explicit-void')
675 return // Explicit void return
676 },
677 onSettled: () => {
678 results.push('onSettled-return-value')
679 return 'ignored-value' // Non-void return (should be ignored)
680 },
681 },
682 'vars',
683 )
684 await vi.advanceTimersByTimeAsync(0)
685 expect(results).toEqual([
686 'onMutate-sync',
687 'onSuccess-implicit-void',
688 'onSettled-return-value',
689 ])
690 })
691β
692 it('should handle all async callback patterns', async () => {
693 const key = queryKey()
694 const results: Array<string> = []
695β
696 executeMutation(
697 queryClient,
698 {
699 mutationKey: key,
700 mutationFn: () => Promise.resolve('success'),
701 onMutate: async () => {
702 results.push('onMutate-async')
703 await sleep(10)
704 return { backup: 'async-data' }
705 },
706 onSuccess: async () => {
707 results.push('onSuccess-async-start')
708 await sleep(20)
709 results.push('onSuccess-async-end')
710 // Implicit void return from async
711 },
712 onSettled: () => {
713 results.push('onSettled-promise')
714 return Promise.resolve('also-ignored') // Promise<string> (should be ignored)
715 },
716 },
717 'vars',
718 )
719 await vi.advanceTimersByTimeAsync(30)
720 expect(results).toEqual([
721 'onMutate-async',
722 'onSuccess-async-start',
723 'onSuccess-async-end',
724 'onSettled-promise',
725 ])
726 })
727β
728 it('should handle Promise.all() and Promise.allSettled() patterns', async () => {
729 const key = queryKey()
730 const results: Array<string> = []
731β
732 executeMutation(
733 queryClient,
734 {
735 mutationKey: key,
736 mutationFn: () => Promise.resolve('success'),
737 onSuccess: () => {
738 results.push('onSuccess-start')
739 return Promise.all([
740 sleep(20).then(() => results.push('invalidate-queries')),
741 sleep(10).then(() => results.push('track-analytics')),
742 ])
743 },
744 onSettled: () => {
745 results.push('onSettled-start')
746 return Promise.allSettled([
747 sleep(10).then(() => results.push('cleanup-1')),
748 Promise.reject('error').catch(() =>
749 results.push('cleanup-2-failed'),
750 ),
751 ])
752 },
753 },
754 'vars',
755 )
756 await vi.advanceTimersByTimeAsync(30)
757 expect(results).toEqual([
758 'onSuccess-start',
759 'track-analytics',
760 'invalidate-queries',
761 'onSettled-start',
762 'cleanup-2-failed',
763 'cleanup-1',
764 ])
765 })
766β
767 it('should handle mixed sync/async patterns and return value isolation', async () => {
768 const key = queryKey()
769 const results: Array<string> = []
770β
771 const mutationPromise = executeMutation(
772 queryClient,
773 {
774 mutationKey: key,
775 mutationFn: () => Promise.resolve('actual-result'),
776 onMutate: () => {
777 results.push('sync-onMutate')
778 return { rollback: 'data' }
779 },
780 onSuccess: async () => {
781 results.push('async-onSuccess')
782 await sleep(10)
783 return 'success-return-ignored'
784 },
785 onError: () => {
786 results.push('sync-onError')
787 return Promise.resolve('error-return-ignored')
788 },
789 onSettled: (_data, _error, _variables, onMutateResult) => {
790 results.push(`settled-onMutateResult-${onMutateResult?.rollback}`)
791 return Promise.all([
792 Promise.resolve('cleanup-1'),
793 Promise.resolve('cleanup-2'),
794 ])
795 },
796 },
797 'vars',
798 )
799 await vi.advanceTimersByTimeAsync(10)
800β
801 const mutationResult = await mutationPromise
802β
803 // Verify mutation returns its own result, not callback returns
804 expect(mutationResult).toBe('actual-result')
805 console.log(results)
806 expect(results).toEqual([
807 'sync-onMutate',
808 'async-onSuccess',
809 'settled-onMutateResult-data',
810 ])
811 })
812β
813 it('should handle error cases with all callback patterns', async () => {
814 const key = queryKey()
815 const results: Array<string> = []
816β
817 const newMutationError = new Error('mutation-error')
818 let mutationError: Error | undefined
819 executeMutation(
820 queryClient,
821 {
822 mutationKey: key,
823 mutationFn: () => Promise.reject(newMutationError),
824 onMutate: () => {
825 results.push('onMutate')
826 return { backup: 'error-data' }
827 },
828 onSuccess: () => {
829 results.push('onSuccess-should-not-run')
830 },
831 onError: async () => {
832 results.push('onError-async')
833 await sleep(10)
834 // Test Promise.all() in error callback
835 return Promise.all([
836 sleep(10).then(() => results.push('error-cleanup-1')),
837 sleep(20).then(() => results.push('error-cleanup-2')),
838 ])
839 },
840 onSettled: (_data, _error, _variables, onMutateResult) => {
841 results.push(`settled-error-${onMutateResult?.backup}`)
842 return Promise.allSettled([
843 Promise.resolve('settled-cleanup'),
844 Promise.reject('settled-error'),
845 ])
846 },
847 },
848 'vars',
849 ).catch((error) => {
850 mutationError = error
851 })
852 await vi.advanceTimersByTimeAsync(30)
853 expect(results).toEqual([
854 'onMutate',
855 'onError-async',
856 'error-cleanup-1',
857 'error-cleanup-2',
858 'settled-error-error-data',
859 ])
860β
861 expect(mutationError).toEqual(newMutationError)
862 })
863 })
864β
865 describe('erroneous mutation callback', () => {
866 it('should trigger onError callback on error by global onSuccess', async () => {
867 const newMutationError = new Error('mutation-error')
868β
869 queryClient = new QueryClient({
870 mutationCache: new MutationCache({
871 onSuccess: () => {
872 throw newMutationError
873 },
874 }),
875 })
876 queryClient.mount()
877β
878 const key = queryKey()
879 const results: Array<string> = []
880β
881 let mutationError: Error | undefined
882 executeMutation(
883 queryClient,
884 {
885 mutationKey: key,
886 mutationFn: () => Promise.resolve('success'),
887 onMutate: async () => {
888 results.push('onMutate-async')
889 await sleep(10)
890 return { backup: 'async-data' }
891 },
892 onSuccess: async () => {
893 results.push('onSuccess-async-start')
894 await sleep(10)
895 throw newMutationError
896 },
897 onError: async () => {
898 results.push('onError-async-start')
899 await sleep(10)
900 results.push('onError-async-end')
901 },
902 onSettled: () => {
903 results.push('onSettled-promise')
904 return Promise.resolve('also-ignored') // Promise<string> (should be ignored)
905 },
906 },
907 'vars',
908 ).catch((error) => {
909 mutationError = error
910 })
911 await vi.advanceTimersByTimeAsync(30)
912 expect(results).toEqual([
913 'onMutate-async',
914 'onError-async-start',
915 'onError-async-end',
916 'onSettled-promise',
917 ])
918β
919 expect(mutationError).toEqual(newMutationError)
920 })
921β
922 it('should trigger onError callback on error by mutations onSuccess', async () => {
923 const key = queryKey()
924 const results: Array<string> = []
925β
926 const newMutationError = new Error('mutation-error')
927β
928 let mutationError: Error | undefined
929 executeMutation(
930 queryClient,
931 {
932 mutationKey: key,
933 mutationFn: () => Promise.resolve('success'),
934 onMutate: async () => {
935 results.push('onMutate-async')
936 await sleep(10)
937 return { backup: 'async-data' }
938 },
939 onSuccess: async () => {
940 results.push('onSuccess-async-start')
941 await sleep(10)
942 throw newMutationError
943 },
944 onError: async () => {
945 results.push('onError-async-start')
946 await sleep(10)
947 results.push('onError-async-end')
948 },
949 onSettled: () => {
950 results.push('onSettled-promise')
951 return Promise.resolve('also-ignored') // Promise<string> (should be ignored)
952 },
953 },
954 'vars',
955 ).catch((error) => {
956 mutationError = error
957 })
958 await vi.advanceTimersByTimeAsync(30)
959 expect(results).toEqual([
960 'onMutate-async',
961 'onSuccess-async-start',
962 'onError-async-start',
963 'onError-async-end',
964 'onSettled-promise',
965 ])
966β
967 expect(mutationError).toEqual(newMutationError)
968 })
969β
970 it('should trigger onError callback on error by global onSettled, calling global onSettled callback twice', async ({
971 onTestFinished,
972 }) => {
973 const newMutationError = new Error('mutation-error')
974β
975 queryClient = new QueryClient({
976 mutationCache: new MutationCache({
977 onSettled: async () => {
978 results.push('global-onSettled')
979 await sleep(10)
980 throw newMutationError
981 },
982 }),
983 })
984 queryClient.mount()
985β
986 const unhandledRejectionFn = vi.fn()
987 process.on('unhandledRejection', unhandledRejectionFn)
988 onTestFinished(() => {
989 process.off('unhandledRejection', unhandledRejectionFn)
990 })
991β
992 const key = queryKey()
993 const results: Array<string> = []
994β
995 let mutationError: Error | undefined
996 executeMutation(
997 queryClient,
998 {
999 mutationKey: key,
1000 mutationFn: () => Promise.resolve('success'),
1001 onMutate: async () => {
1002 results.push('onMutate-async')
1003 await sleep(10)
1004 return { backup: 'async-data' }
1005 },
1006 onSuccess: async () => {
1007 results.push('onSuccess-async-start')
1008 await sleep(10)
1009 results.push('onSuccess-async-end')
1010 },
1011 onError: async () => {
1012 results.push('onError-async-start')
1013 await sleep(10)
1014 results.push('onError-async-end')
1015 },
1016 onSettled: () => {
1017 results.push('local-onSettled')
1018 },
1019 },
1020 'vars',
1021 ).catch((error) => {
1022 mutationError = error
1023 })
1024 await vi.advanceTimersByTimeAsync(50)
1025 expect(results).toEqual([
1026 'onMutate-async',
1027 'onSuccess-async-start',
1028 'onSuccess-async-end',
1029 'global-onSettled',
1030 'onError-async-start',
1031 'onError-async-end',
1032 'global-onSettled',
1033 'local-onSettled',
1034 ])
1035β
1036 expect(unhandledRejectionFn).toHaveBeenCalledTimes(1)
1037 expect(unhandledRejectionFn).toHaveBeenNthCalledWith(
1038 1,
1039 newMutationError,
1040 expect.any(Promise),
1041 )
1042β
1043 expect(mutationError).toEqual(newMutationError)
1044 })
1045β
1046 it('should trigger onError callback on error by mutations onSettled, calling both onSettled callbacks twice', async ({
1047 onTestFinished,
1048 }) => {
1049 const unhandledRejectionFn = vi.fn()
1050 process.on('unhandledRejection', unhandledRejectionFn)
1051 onTestFinished(() => {
1052 process.off('unhandledRejection', unhandledRejectionFn)
1053 })
1054β
1055 const key = queryKey()
1056 const results: Array<string> = []
1057β
1058 const newMutationError = new Error('mutation-error')
1059β
1060 let mutationError: Error | undefined
1061 executeMutation(
1062 queryClient,
1063 {
1064 mutationKey: key,
1065 mutationFn: () => Promise.resolve('success'),
1066 onMutate: async () => {
1067 results.push('onMutate-async')
1068 await sleep(10)
1069 return { backup: 'async-data' }
1070 },
1071 onSuccess: async () => {
1072 results.push('onSuccess-async-start')
1073 await sleep(10)
1074 results.push('onSuccess-async-end')
1075 },
1076 onError: async () => {
1077 results.push('onError-async-start')
1078 await sleep(10)
1079 results.push('onError-async-end')
1080 },
1081 onSettled: async () => {
1082 results.push('onSettled-async-promise')
1083 await sleep(10)
1084 throw newMutationError
1085 },
1086 },
1087 'vars',
1088 ).catch((error) => {
1089 mutationError = error
1090 })
1091 await vi.advanceTimersByTimeAsync(50)
1092 expect(results).toEqual([
1093 'onMutate-async',
1094 'onSuccess-async-start',
1095 'onSuccess-async-end',
1096 'onSettled-async-promise',
1097 'onError-async-start',
1098 'onError-async-end',
1099 'onSettled-async-promise',
1100 ])
1101β
1102 expect(unhandledRejectionFn).toHaveBeenCalledTimes(1)
1103 expect(unhandledRejectionFn).toHaveBeenNthCalledWith(
1104 1,
1105 newMutationError,
1106 expect.any(Promise),
1107 )
1108β
1109 expect(mutationError).toEqual(newMutationError)
1110 })
1111β
1112 it('should transfer errors by onError and consecutive onSettled callbacks to different execution context where they are reported', async ({
1113 onTestFinished,
1114 }) => {
1115 const unhandledRejectionFn = vi.fn()
1116 process.on('unhandledRejection', unhandledRejectionFn)
1117 onTestFinished(() => {
1118 process.off('unhandledRejection', unhandledRejectionFn)
1119 })
1120β
1121 const globalErrorError = new Error('global-error-error')
1122 const globalSettledError = new Error('global-settled-error')
1123β
1124 queryClient = new QueryClient({
1125 mutationCache: new MutationCache({
1126 onError: () => {
1127 throw globalErrorError
1128 },
1129 onSettled: () => {
1130 throw globalSettledError
1131 },
1132 }),
1133 })
1134 queryClient.mount()
1135β
1136 const key = queryKey()
1137 const results: Array<string> = []
1138β
1139 const newMutationError = new Error('mutation-error')
1140 const newErrorError = new Error('error-error')
1141 const newSettledError = new Error('settled-error')
1142β
1143 let mutationError: Error | undefined
1144 executeMutation(
1145 queryClient,
1146 {
1147 mutationKey: key,
1148 mutationFn: () => Promise.resolve('success'),
1149 onMutate: async () => {
1150 results.push('onMutate-async')
1151 await sleep(10)
1152 throw newMutationError
1153 },
1154 onSuccess: () => {
1155 results.push('onSuccess-async-start')
1156 },
1157 onError: async () => {
1158 results.push('onError-async-start')
1159 await sleep(10)
1160 throw newErrorError
1161 },
1162 onSettled: async () => {
1163 results.push('onSettled-promise')
1164 await sleep(10)
1165 throw newSettledError
1166 },
1167 },
1168 'vars',
1169 ).catch((error) => {
1170 mutationError = error
1171 })
1172 await vi.advanceTimersByTimeAsync(30)
1173 expect(results).toEqual([
1174 'onMutate-async',
1175 'onError-async-start',
1176 'onSettled-promise',
1177 ])
1178β
1179 expect(mutationError).toEqual(newMutationError)
1180β
1181 expect(unhandledRejectionFn).toHaveBeenCalledTimes(4)
1182 expect(unhandledRejectionFn).toHaveBeenNthCalledWith(
1183 1,
1184 globalErrorError,
1185 expect.any(Promise),
1186 )
1187 expect(unhandledRejectionFn).toHaveBeenNthCalledWith(
1188 2,
1189 newErrorError,
1190 expect.any(Promise),
1191 )
1192 expect(unhandledRejectionFn).toHaveBeenNthCalledWith(
1193 3,
1194 globalSettledError,
1195 expect.any(Promise),
1196 )
1197 expect(unhandledRejectionFn).toHaveBeenNthCalledWith(
1198 4,
1199 newSettledError,
1200 expect.any(Promise),
1201 )
1202 })
1203 })
1204β
1205 it('should not remove mutation when one observer is removed but another still exists', async () => {
1206 const observer1 = new MutationObserver(queryClient, {
1207 gcTime: 10,
1208 mutationFn: () => sleep(10).then(() => 'data'),
1209 })
1210 const unsubscribe1 = observer1.subscribe(() => undefined)
1211β
1212 observer1.mutate()
1213 await vi.advanceTimersByTimeAsync(10)
1214 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
1215β
1216 const mutation = queryClient.getMutationCache().getAll()[0]!
1217 const observer2 = new MutationObserver(queryClient, {
1218 gcTime: 10,
1219 mutationFn: () => sleep(10).then(() => 'data'),
1220 })
1221 mutation.addObserver(observer2)
1222β
1223 unsubscribe1()
1224 await vi.advanceTimersByTimeAsync(10)
1225 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
1226 })
1227β
1228 it('should release the retryer once a mutation settles', async () => {
1229 const observer = new MutationObserver(queryClient, {
1230 mutationFn: (text: string) => sleep(10).then(() => text),
1231 })
1232β
1233 observer.mutate('data')
1234 await vi.advanceTimersByTimeAsync(10)
1235β
1236 const mutation = queryClient.getMutationCache().getAll()[0]!
1237 expect(mutation.state.status).toBe('success')
1238β
1239 // continue() is the only reader of the retryer outside execute(): while a
1240 // settled retryer is still referenced it hands back that retryer's promise,
1241 // which resolves with the raw result it closed over
1242 await expect(mutation.continue()).resolves.toBeUndefined()
1243 })
1244β
1245 it('should release the retryer of a mutation that settled with an error', async () => {
1246 const observer = new MutationObserver(queryClient, {
1247 mutationFn: () => sleep(10).then(() => Promise.reject(new Error('oops'))),
1248 })
1249β
1250 observer.mutate(undefined).catch(() => undefined)
1251 await vi.advanceTimersByTimeAsync(10)
1252β
1253 const mutation = queryClient.getMutationCache().getAll()[0]!
1254 expect(mutation.state.status).toBe('error')
1255β
1256 // a retained retryer would hand back its rejected promise here
1257 await expect(mutation.continue()).resolves.toBeUndefined()
1258 })
1259β
1260 it('should not re-execute a settled mutation when it is continued', async () => {
1261 const mutationFn = vi.fn(() => sleep(10).then(() => 'data'))
1262 const observer = new MutationObserver(queryClient, { mutationFn })
1263β
1264 observer.mutate()
1265 await vi.advanceTimersByTimeAsync(10)
1266β
1267 const mutation = queryClient.getMutationCache().getAll()[0]!
1268 expect(mutation.state.status).toBe('success')
1269 expect(mutationFn).toHaveBeenCalledTimes(1)
1270β
1271 await mutation.continue()
1272 await vi.advanceTimersByTimeAsync(10)
1273 expect(mutationFn).toHaveBeenCalledTimes(1)
1274 expect(mutation.state.status).toBe('success')
1275 })
1276β
1277 it('should still continue a restored paused mutation that has no retryer', async () => {
1278 const mutationFn = vi.fn(() => sleep(10).then(() => 'data'))
1279 // a mutation restored from a dehydrated pending state has no retryer yet
1280 const mutation = queryClient.getMutationCache().build(
1281 queryClient,
1282 { mutationFn },
1283 {
1284 context: undefined,
1285 data: undefined,
1286 error: null,
1287 failureCount: 0,
1288 failureReason: null,
1289 isPaused: true,
1290 status: 'pending',
1291 variables: undefined,
1292 submittedAt: Date.now(),
1293 },
1294 )
1295β
1296 const continued = mutation.continue()
1297 await vi.advanceTimersByTimeAsync(10)
1298 await continued
1299 expect(mutationFn).toHaveBeenCalledTimes(1)
1300 expect(mutation.state.status).toBe('success')
1301 })
1302})