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