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 } 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 it('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 it('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 it('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 it('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 it('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 it('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 it('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 it('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 it('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 it('mutation callbacks should see updated options', async () => {
406 const onSuccess = vi.fn()
407β
408 const mutation = new MutationObserver(queryClient, {
409 mutationFn: () => sleep(100).then(() => Promise.resolve('update')),
410 onSuccess: () => {
411 onSuccess(1)
412 },
413 })
414β
415 void mutation.mutate()
416β
417 mutation.setOptions({
418 mutationFn: () => sleep(100).then(() => Promise.resolve('update')),
419 onSuccess: () => {
420 onSuccess(2)
421 },
422 })
423β
424 await vi.advanceTimersByTimeAsync(100)
425 expect(onSuccess).toHaveBeenCalledTimes(1)
426β
427 expect(onSuccess).toHaveBeenCalledWith(2)
428 })
429β
430 describe('scoped mutations', () => {
431 it('mutations in the same scope should run in serial', async () => {
432 const key1 = queryKey()
433 const key2 = queryKey()
434β
435 const results: Array<string> = []
436β
437 executeMutation(
438 queryClient,
439 {
440 mutationKey: key1,
441 scope: {
442 id: 'scope',
443 },
444 mutationFn: async () => {
445 results.push('start-A')
446 await sleep(10)
447 results.push('finish-A')
448 return 'a'
449 },
450 },
451 'vars1',
452 )
453β
454 expect(
455 queryClient.getMutationCache().find({ mutationKey: key1 })?.state,
456 ).toMatchObject({
457 status: 'pending',
458 isPaused: false,
459 })
460β
461 executeMutation(
462 queryClient,
463 {
464 mutationKey: key2,
465 scope: {
466 id: 'scope',
467 },
468 mutationFn: async () => {
469 results.push('start-B')
470 await sleep(10)
471 results.push('finish-B')
472 return 'b'
473 },
474 },
475 'vars2',
476 )
477β
478 expect(
479 queryClient.getMutationCache().find({ mutationKey: key2 })?.state,
480 ).toMatchObject({
481 status: 'pending',
482 isPaused: true,
483 })
484β
485 await vi.advanceTimersByTimeAsync(20)
486β
487 expect(results).toStrictEqual([
488 'start-A',
489 'finish-A',
490 'start-B',
491 'finish-B',
492 ])
493 })
494 })
495β
496 it('mutations without scope should run in parallel', async () => {
497 const key1 = queryKey()
498 const key2 = queryKey()
499β
500 const results: Array<string> = []
501β
502 executeMutation(
503 queryClient,
504 {
505 mutationKey: key1,
506 mutationFn: async () => {
507 results.push('start-A')
508 await sleep(10)
509 results.push('finish-A')
510 return 'a'
511 },
512 },
513 'vars1',
514 )
515β
516 executeMutation(
517 queryClient,
518 {
519 mutationKey: key2,
520 mutationFn: async () => {
521 results.push('start-B')
522 await sleep(10)
523 results.push('finish-B')
524 return 'b'
525 },
526 },
527 'vars2',
528 )
529β
530 await vi.advanceTimersByTimeAsync(10)
531β
532 expect(results).toStrictEqual([
533 'start-A',
534 'start-B',
535 'finish-A',
536 'finish-B',
537 ])
538 })
539β
540 it('each scope should run in parallel, serial within scope', async () => {
541 const results: Array<string> = []
542β
543 executeMutation(
544 queryClient,
545 {
546 scope: {
547 id: '1',
548 },
549 mutationFn: async () => {
550 results.push('start-A1')
551 await sleep(10)
552 results.push('finish-A1')
553 return 'a'
554 },
555 },
556 'vars1',
557 )
558β
559 executeMutation(
560 queryClient,
561 {
562 scope: {
563 id: '1',
564 },
565 mutationFn: async () => {
566 results.push('start-B1')
567 await sleep(10)
568 results.push('finish-B1')
569 return 'b'
570 },
571 },
572 'vars2',
573 )
574β
575 executeMutation(
576 queryClient,
577 {
578 scope: {
579 id: '2',
580 },
581 mutationFn: async () => {
582 results.push('start-A2')
583 await sleep(10)
584 results.push('finish-A2')
585 return 'a'
586 },
587 },
588 'vars1',
589 )
590β
591 executeMutation(
592 queryClient,
593 {
594 scope: {
595 id: '2',
596 },
597 mutationFn: async () => {
598 results.push('start-B2')
599 await sleep(10)
600 results.push('finish-B2')
601 return 'b'
602 },
603 },
604 'vars2',
605 )
606β
607 await vi.advanceTimersByTimeAsync(20)
608β
609 expect(results).toStrictEqual([
610 'start-A1',
611 'start-A2',
612 'finish-A1',
613 'start-B1',
614 'finish-A2',
615 'start-B2',
616 'finish-B1',
617 'finish-B2',
618 ])
619 })
620β
621 describe('callback return types', () => {
622 it('should handle all sync callback patterns', async () => {
623 const key = queryKey()
624 const results: Array<string> = []
625β
626 executeMutation(
627 queryClient,
628 {
629 mutationKey: key,
630 mutationFn: () => Promise.resolve('success'),
631 onMutate: () => {
632 results.push('onMutate-sync')
633 return { backup: 'data' } // onMutate can return a result
634 },
635 onSuccess: () => {
636 results.push('onSuccess-implicit-void')
637 // Implicit void return
638 },
639 onError: () => {
640 results.push('onError-explicit-void')
641 return // Explicit void return
642 },
643 onSettled: () => {
644 results.push('onSettled-return-value')
645 return 'ignored-value' // Non-void return (should be ignored)
646 },
647 },
648 'vars',
649 )
650β
651 await vi.advanceTimersByTimeAsync(0)
652β
653 expect(results).toEqual([
654 'onMutate-sync',
655 'onSuccess-implicit-void',
656 'onSettled-return-value',
657 ])
658 })
659β
660 it('should handle all async callback patterns', async () => {
661 const key = queryKey()
662 const results: Array<string> = []
663β
664 executeMutation(
665 queryClient,
666 {
667 mutationKey: key,
668 mutationFn: () => Promise.resolve('success'),
669 onMutate: async () => {
670 results.push('onMutate-async')
671 await sleep(10)
672 return { backup: 'async-data' }
673 },
674 onSuccess: async () => {
675 results.push('onSuccess-async-start')
676 await sleep(20)
677 results.push('onSuccess-async-end')
678 // Implicit void return from async
679 },
680 onSettled: () => {
681 results.push('onSettled-promise')
682 return Promise.resolve('also-ignored') // Promise<string> (should be ignored)
683 },
684 },
685 'vars',
686 )
687β
688 await vi.advanceTimersByTimeAsync(30)
689β
690 expect(results).toEqual([
691 'onMutate-async',
692 'onSuccess-async-start',
693 'onSuccess-async-end',
694 'onSettled-promise',
695 ])
696 })
697β
698 it('should handle Promise.all() and Promise.allSettled() patterns', async () => {
699 const key = queryKey()
700 const results: Array<string> = []
701β
702 executeMutation(
703 queryClient,
704 {
705 mutationKey: key,
706 mutationFn: () => Promise.resolve('success'),
707 onSuccess: () => {
708 results.push('onSuccess-start')
709 return Promise.all([
710 sleep(20).then(() => results.push('invalidate-queries')),
711 sleep(10).then(() => results.push('track-analytics')),
712 ])
713 },
714 onSettled: () => {
715 results.push('onSettled-start')
716 return Promise.allSettled([
717 sleep(10).then(() => results.push('cleanup-1')),
718 Promise.reject('error').catch(() =>
719 results.push('cleanup-2-failed'),
720 ),
721 ])
722 },
723 },
724 'vars',
725 )
726β
727 await vi.advanceTimersByTimeAsync(30)
728β
729 expect(results).toEqual([
730 'onSuccess-start',
731 'track-analytics',
732 'invalidate-queries',
733 'onSettled-start',
734 'cleanup-2-failed',
735 'cleanup-1',
736 ])
737 })
738β
739 it('should handle mixed sync/async patterns and return value isolation', async () => {
740 const key = queryKey()
741 const results: Array<string> = []
742β
743 const mutationPromise = executeMutation(
744 queryClient,
745 {
746 mutationKey: key,
747 mutationFn: () => Promise.resolve('actual-result'),
748 onMutate: () => {
749 results.push('sync-onMutate')
750 return { rollback: 'data' }
751 },
752 onSuccess: async () => {
753 results.push('async-onSuccess')
754 await sleep(10)
755 return 'success-return-ignored'
756 },
757 onError: () => {
758 results.push('sync-onError')
759 return Promise.resolve('error-return-ignored')
760 },
761 onSettled: (_data, _error, _variables, onMutateResult) => {
762 results.push(`settled-onMutateResult-${onMutateResult?.rollback}`)
763 return Promise.all([
764 Promise.resolve('cleanup-1'),
765 Promise.resolve('cleanup-2'),
766 ])
767 },
768 },
769 'vars',
770 )
771β
772 await vi.advanceTimersByTimeAsync(10)
773β
774 const mutationResult = await mutationPromise
775β
776 // Verify mutation returns its own result, not callback returns
777 expect(mutationResult).toBe('actual-result')
778 console.log(results)
779 expect(results).toEqual([
780 'sync-onMutate',
781 'async-onSuccess',
782 'settled-onMutateResult-data',
783 ])
784 })
785β
786 it('should handle error cases with all callback patterns', async () => {
787 const key = queryKey()
788 const results: Array<string> = []
789β
790 const newMutationError = new Error('mutation-error')
791 let mutationError: Error | undefined
792 executeMutation(
793 queryClient,
794 {
795 mutationKey: key,
796 mutationFn: () => Promise.reject(newMutationError),
797 onMutate: () => {
798 results.push('onMutate')
799 return { backup: 'error-data' }
800 },
801 onSuccess: () => {
802 results.push('onSuccess-should-not-run')
803 },
804 onError: async () => {
805 results.push('onError-async')
806 await sleep(10)
807 // Test Promise.all() in error callback
808 return Promise.all([
809 sleep(10).then(() => results.push('error-cleanup-1')),
810 sleep(20).then(() => results.push('error-cleanup-2')),
811 ])
812 },
813 onSettled: (_data, _error, _variables, onMutateResult) => {
814 results.push(`settled-error-${onMutateResult?.backup}`)
815 return Promise.allSettled([
816 Promise.resolve('settled-cleanup'),
817 Promise.reject('settled-error'),
818 ])
819 },
820 },
821 'vars',
822 ).catch((error) => {
823 mutationError = error
824 })
825β
826 await vi.advanceTimersByTimeAsync(30)
827β
828 expect(results).toEqual([
829 'onMutate',
830 'onError-async',
831 'error-cleanup-1',
832 'error-cleanup-2',
833 'settled-error-error-data',
834 ])
835β
836 expect(mutationError).toEqual(newMutationError)
837 })
838 })
839β
840 describe('erroneous mutation callback', () => {
841 it('error by global onSuccess triggers onError callback', async () => {
842 const newMutationError = new Error('mutation-error')
843β
844 queryClient = new QueryClient({
845 mutationCache: new MutationCache({
846 onSuccess: () => {
847 throw newMutationError
848 },
849 }),
850 })
851 queryClient.mount()
852β
853 const key = queryKey()
854 const results: Array<string> = []
855β
856 let mutationError: Error | undefined
857 executeMutation(
858 queryClient,
859 {
860 mutationKey: key,
861 mutationFn: () => Promise.resolve('success'),
862 onMutate: async () => {
863 results.push('onMutate-async')
864 await sleep(10)
865 return { backup: 'async-data' }
866 },
867 onSuccess: async () => {
868 results.push('onSuccess-async-start')
869 await sleep(10)
870 throw newMutationError
871 },
872 onError: async () => {
873 results.push('onError-async-start')
874 await sleep(10)
875 results.push('onError-async-end')
876 },
877 onSettled: () => {
878 results.push('onSettled-promise')
879 return Promise.resolve('also-ignored') // Promise<string> (should be ignored)
880 },
881 },
882 'vars',
883 ).catch((error) => {
884 mutationError = error
885 })
886β
887 await vi.advanceTimersByTimeAsync(30)
888β
889 expect(results).toEqual([
890 'onMutate-async',
891 'onError-async-start',
892 'onError-async-end',
893 'onSettled-promise',
894 ])
895β
896 expect(mutationError).toEqual(newMutationError)
897 })
898β
899 it('error by mutations onSuccess triggers onError callback', async () => {
900 const key = queryKey()
901 const results: Array<string> = []
902β
903 const newMutationError = new Error('mutation-error')
904β
905 let mutationError: Error | undefined
906 executeMutation(
907 queryClient,
908 {
909 mutationKey: key,
910 mutationFn: () => Promise.resolve('success'),
911 onMutate: async () => {
912 results.push('onMutate-async')
913 await sleep(10)
914 return { backup: 'async-data' }
915 },
916 onSuccess: async () => {
917 results.push('onSuccess-async-start')
918 await sleep(10)
919 throw newMutationError
920 },
921 onError: async () => {
922 results.push('onError-async-start')
923 await sleep(10)
924 results.push('onError-async-end')
925 },
926 onSettled: () => {
927 results.push('onSettled-promise')
928 return Promise.resolve('also-ignored') // Promise<string> (should be ignored)
929 },
930 },
931 'vars',
932 ).catch((error) => {
933 mutationError = error
934 })
935β
936 await vi.advanceTimersByTimeAsync(30)
937β
938 expect(results).toEqual([
939 'onMutate-async',
940 'onSuccess-async-start',
941 'onError-async-start',
942 'onError-async-end',
943 'onSettled-promise',
944 ])
945β
946 expect(mutationError).toEqual(newMutationError)
947 })
948β
949 it('error by global onSettled triggers onError callback, calling global onSettled callback twice', async ({
950 onTestFinished,
951 }) => {
952 const newMutationError = new Error('mutation-error')
953β
954 queryClient = new QueryClient({
955 mutationCache: new MutationCache({
956 onSettled: async () => {
957 results.push('global-onSettled')
958 await sleep(10)
959 throw newMutationError
960 },
961 }),
962 })
963 queryClient.mount()
964β
965 const unhandledRejectionFn = vi.fn()
966 process.on('unhandledRejection', (error) => unhandledRejectionFn(error))
967 onTestFinished(() => {
968 process.off('unhandledRejection', unhandledRejectionFn)
969 })
970β
971 const key = queryKey()
972 const results: Array<string> = []
973β
974 let mutationError: Error | undefined
975 executeMutation(
976 queryClient,
977 {
978 mutationKey: key,
979 mutationFn: () => Promise.resolve('success'),
980 onMutate: async () => {
981 results.push('onMutate-async')
982 await sleep(10)
983 return { backup: 'async-data' }
984 },
985 onSuccess: async () => {
986 results.push('onSuccess-async-start')
987 await sleep(10)
988 results.push('onSuccess-async-end')
989 },
990 onError: async () => {
991 results.push('onError-async-start')
992 await sleep(10)
993 results.push('onError-async-end')
994 },
995 onSettled: () => {
996 results.push('local-onSettled')
997 },
998 },
999 'vars',
1000 ).catch((error) => {
1001 mutationError = error
1002 })
1003β
1004 await vi.advanceTimersByTimeAsync(50)
1005β
1006 expect(results).toEqual([
1007 'onMutate-async',
1008 'onSuccess-async-start',
1009 'onSuccess-async-end',
1010 'global-onSettled',
1011 'onError-async-start',
1012 'onError-async-end',
1013 'global-onSettled',
1014 'local-onSettled',
1015 ])
1016β
1017 expect(unhandledRejectionFn).toHaveBeenCalledTimes(1)
1018 expect(unhandledRejectionFn).toHaveBeenNthCalledWith(1, newMutationError)
1019β
1020 expect(mutationError).toEqual(newMutationError)
1021 })
1022β
1023 it('error by mutations onSettled triggers onError callback, calling both onSettled callbacks twice', async ({
1024 onTestFinished,
1025 }) => {
1026 const unhandledRejectionFn = vi.fn()
1027 process.on('unhandledRejection', (error) => unhandledRejectionFn(error))
1028 onTestFinished(() => {
1029 process.off('unhandledRejection', unhandledRejectionFn)
1030 })
1031β
1032 const key = queryKey()
1033 const results: Array<string> = []
1034β
1035 const newMutationError = new Error('mutation-error')
1036β
1037 let mutationError: Error | undefined
1038 executeMutation(
1039 queryClient,
1040 {
1041 mutationKey: key,
1042 mutationFn: () => Promise.resolve('success'),
1043 onMutate: async () => {
1044 results.push('onMutate-async')
1045 await sleep(10)
1046 return { backup: 'async-data' }
1047 },
1048 onSuccess: async () => {
1049 results.push('onSuccess-async-start')
1050 await sleep(10)
1051 results.push('onSuccess-async-end')
1052 },
1053 onError: async () => {
1054 results.push('onError-async-start')
1055 await sleep(10)
1056 results.push('onError-async-end')
1057 },
1058 onSettled: async () => {
1059 results.push('onSettled-async-promise')
1060 await sleep(10)
1061 throw newMutationError
1062 },
1063 },
1064 'vars',
1065 ).catch((error) => {
1066 mutationError = error
1067 })
1068β
1069 await vi.advanceTimersByTimeAsync(50)
1070β
1071 expect(results).toEqual([
1072 'onMutate-async',
1073 'onSuccess-async-start',
1074 'onSuccess-async-end',
1075 'onSettled-async-promise',
1076 'onError-async-start',
1077 'onError-async-end',
1078 'onSettled-async-promise',
1079 ])
1080β
1081 expect(unhandledRejectionFn).toHaveBeenCalledTimes(1)
1082 expect(unhandledRejectionFn).toHaveBeenNthCalledWith(1, newMutationError)
1083β
1084 expect(mutationError).toEqual(newMutationError)
1085 })
1086β
1087 it('errors by onError and consecutive onSettled callbacks are transferred to different execution context where it are reported', async ({
1088 onTestFinished,
1089 }) => {
1090 const unhandledRejectionFn = vi.fn()
1091 process.on('unhandledRejection', (error) => unhandledRejectionFn(error))
1092 onTestFinished(() => {
1093 process.off('unhandledRejection', unhandledRejectionFn)
1094 })
1095β
1096 const globalErrorError = new Error('global-error-error')
1097 const globalSettledError = new Error('global-settled-error')
1098β
1099 queryClient = new QueryClient({
1100 mutationCache: new MutationCache({
1101 onError: () => {
1102 throw globalErrorError
1103 },
1104 onSettled: () => {
1105 throw globalSettledError
1106 },
1107 }),
1108 })
1109 queryClient.mount()
1110β
1111 const key = queryKey()
1112 const results: Array<string> = []
1113β
1114 const newMutationError = new Error('mutation-error')
1115 const newErrorError = new Error('error-error')
1116 const newSettledError = new Error('settled-error')
1117β
1118 let mutationError: Error | undefined
1119 executeMutation(
1120 queryClient,
1121 {
1122 mutationKey: key,
1123 mutationFn: () => Promise.resolve('success'),
1124 onMutate: async () => {
1125 results.push('onMutate-async')
1126 await sleep(10)
1127 throw newMutationError
1128 },
1129 onSuccess: () => {
1130 results.push('onSuccess-async-start')
1131 },
1132 onError: async () => {
1133 results.push('onError-async-start')
1134 await sleep(10)
1135 throw newErrorError
1136 },
1137 onSettled: async () => {
1138 results.push('onSettled-promise')
1139 await sleep(10)
1140 throw newSettledError
1141 },
1142 },
1143 'vars',
1144 ).catch((error) => {
1145 mutationError = error
1146 })
1147β
1148 await vi.advanceTimersByTimeAsync(30)
1149β
1150 expect(results).toEqual([
1151 'onMutate-async',
1152 'onError-async-start',
1153 'onSettled-promise',
1154 ])
1155β
1156 expect(mutationError).toEqual(newMutationError)
1157β
1158 expect(unhandledRejectionFn).toHaveBeenCalledTimes(4)
1159 expect(unhandledRejectionFn).toHaveBeenNthCalledWith(1, globalErrorError)
1160 expect(unhandledRejectionFn).toHaveBeenNthCalledWith(2, newErrorError)
1161 expect(unhandledRejectionFn).toHaveBeenNthCalledWith(
1162 3,
1163 globalSettledError,
1164 )
1165 expect(unhandledRejectionFn).toHaveBeenNthCalledWith(4, newSettledError)
1166 })
1167 })
1168β
1169 it('should not remove mutation when one observer is removed but another still exists', async () => {
1170 const observer1 = new MutationObserver(queryClient, {
1171 gcTime: 10,
1172 mutationFn: () => sleep(10).then(() => 'data'),
1173 })
1174 const unsubscribe1 = observer1.subscribe(() => undefined)
1175β
1176 observer1.mutate()
1177 await vi.advanceTimersByTimeAsync(10)
1178β
1179 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
1180β
1181 const mutation = queryClient.getMutationCache().getAll()[0]!
1182 const observer2 = new MutationObserver(queryClient, {
1183 gcTime: 10,
1184 mutationFn: () => sleep(10).then(() => 'data'),
1185 })
1186 mutation.addObserver(observer2)
1187β
1188 unsubscribe1()
1189β
1190 await vi.advanceTimersByTimeAsync(10)
1191β
1192 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
1193 })
1194})