Open History to see the last commit
1import { noop } from '@tanstack/query-core'
2import { createKey, sleep } from '@tanstack/query-test-utils'
3import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
4import {
5 isReactive,
6 isReadonly,
7 isVue2,
8 isVue3,
9 onScopeDispose,
10 reactive,
11 ref,
12} from 'vue-demi'
13import { useMutation } from '../useMutation'
14import { useQueryClient } from '../useQueryClient'
15import type { MutationFunctionContext } from '@tanstack/query-core'
16β
17vi.mock(import('../useQueryClient'))
18β
19describe('useMutation', () => {
20 beforeEach(() => {
21 vi.useFakeTimers()
22 })
23β
24 afterEach(() => {
25 vi.useRealTimers()
26 })
27β
28 it('should be in idle state initially', () => {
29 const mutation = useMutation({
30 mutationFn: (params) => sleep(0).then(() => params),
31 })
32β
33 expect(mutation).toMatchObject({
34 isIdle: { value: true },
35 isPending: { value: false },
36 isError: { value: false },
37 isSuccess: { value: false },
38 })
39 })
40β
41 it('should change state after invoking mutate', () => {
42 const result = 'Mock data'
43 const mutation = useMutation({
44 mutationFn: (params: string) => sleep(0).then(() => params),
45 })
46β
47 mutation.mutate(result)
48 expect(mutation).toMatchObject({
49 isIdle: { value: false },
50 isPending: { value: true },
51 isError: { value: false },
52 isSuccess: { value: false },
53 data: { value: undefined },
54 error: { value: null },
55 })
56 })
57β
58 it('should return error when request fails', async () => {
59 const mutation = useMutation({
60 mutationFn: () =>
61 sleep(10).then(() => Promise.reject(new Error('Some error'))),
62 })
63 mutation.mutate()
64 await vi.advanceTimersByTimeAsync(10)
65 expect(mutation).toMatchObject({
66 isIdle: { value: false },
67 isPending: { value: false },
68 isError: { value: true },
69 isSuccess: { value: false },
70 data: { value: undefined },
71 error: { value: Error('Some error') },
72 })
73 })
74β
75 it('should return data when request succeeds', async () => {
76 const result = 'Mock data'
77 const mutation = useMutation({
78 mutationFn: (params: string) => sleep(10).then(() => params),
79 })
80β
81 mutation.mutate(result)
82 await vi.advanceTimersByTimeAsync(10)
83 expect(mutation).toMatchObject({
84 isIdle: { value: false },
85 isPending: { value: false },
86 isError: { value: false },
87 isSuccess: { value: true },
88 data: { value: 'Mock data' },
89 error: { value: null },
90 })
91 })
92β
93 it('should work with options getter and be reactive', async () => {
94 const key = createKey()
95 const result = 'Mock data'
96 const keyRef = ref('key01')
97 const mutationFn = vi.fn<(params: string) => Promise<string>>(
98 (params: string) => sleep(10).then(() => params),
99 )
100 const mutation = useMutation(() => ({
101 mutationKey: [...key, keyRef.value],
102 mutationFn,
103 }))
104β
105 mutation.mutate(result)
106 await vi.advanceTimersByTimeAsync(10)
107 expect(mutationFn).toHaveBeenCalledTimes(1)
108 expect(mutationFn).toHaveBeenNthCalledWith(
109 1,
110 result,
111 expect.objectContaining({ mutationKey: [...key, 'key01'] }),
112 )
113β
114 keyRef.value = 'key02'
115 await vi.advanceTimersByTimeAsync(0)
116 mutation.mutate(result)
117 await vi.advanceTimersByTimeAsync(10)
118 expect(mutationFn).toHaveBeenCalledTimes(2)
119 expect(mutationFn).toHaveBeenNthCalledWith(
120 2,
121 result,
122 expect.objectContaining({ mutationKey: [...key, 'key02'] }),
123 )
124 })
125β
126 it('should update reactive options', async () => {
127 const key1 = createKey()
128 const key2 = createKey()
129 const queryClient = useQueryClient()
130 const mutationCache = queryClient.getMutationCache()
131 const options = reactive({
132 mutationKey: key1,
133 mutationFn: (params: string) => sleep(10).then(() => params),
134 })
135 const mutation = useMutation(options)
136β
137 options.mutationKey = key2
138 await vi.advanceTimersByTimeAsync(10)
139 mutation.mutate('xyz')
140 await vi.advanceTimersByTimeAsync(10)
141 const mutations = mutationCache.find({ mutationKey: key2 })
142 expect(mutations?.options.mutationKey).toStrictEqual(key2)
143 })
144β
145 it('should update reactive options deeply', async () => {
146 type MutationKeyTest = {
147 entity: string
148 otherObject: {
149 name: string
150 }
151 }
152 const mutationKey = ref<Array<MutationKeyTest>>([
153 {
154 entity: 'test',
155 otherObject: { name: 'objectName' },
156 },
157 ])
158 const queryClient = useQueryClient()
159 const mutationCache = queryClient.getMutationCache()
160 const options = reactive({
161 mutationKey,
162 mutationFn: (params: string) => sleep(10).then(() => params),
163 })
164 const mutation = useMutation(options)
165β
166 mutationKey.value[0]!.otherObject.name = 'someOtherObjectName'
167 await vi.advanceTimersByTimeAsync(10)
168 mutation.mutate('xyz')
169 await vi.advanceTimersByTimeAsync(10)
170β
171 const mutations = mutationCache.getAll()
172 const relevantMutation = mutations.find((m) => {
173 return (
174 Array.isArray(m.options.mutationKey) &&
175 !!m.options.mutationKey[0].otherObject
176 )
177 })
178β
179 expect(
180 (
181 relevantMutation?.options.mutationKey as
182 | Array<MutationKeyTest>
183 | undefined
184 )?.[0]?.otherObject.name,
185 ).toBe('someOtherObjectName')
186 })
187β
188 it('should allow for non-options object (mutationFn or mutationKey) passed as arg1 & arg2 to trigger reactive updates', async () => {
189 const key1 = createKey()
190 const key2 = createKey()
191 const mutationKeyRef = ref<Array<string>>(key1)
192 const mutationFn = ref((params: string) => sleep(0).then(() => params))
193 const queryClient = useQueryClient()
194 const mutationCache = queryClient.getMutationCache()
195 const mutation = useMutation({ mutationKey: mutationKeyRef, mutationFn })
196β
197 mutationKeyRef.value = key2
198 let proof = false
199 mutationFn.value = (params: string) => {
200 proof = true
201 return sleep(10).then(() => params)
202 }
203 await vi.advanceTimersByTimeAsync(10)
204β
205 mutation.mutate('xyz')
206 await vi.advanceTimersByTimeAsync(10)
207β
208 const mutations = mutationCache.find({ mutationKey: key2 })
209 expect(mutations?.options.mutationKey).toStrictEqual(key2)
210 expect(proof).toBe(true)
211 })
212β
213 it('should reset state after invoking mutation.reset', async () => {
214 const mutation = useMutation({
215 mutationFn: () =>
216 sleep(10).then(() => Promise.reject(new Error('Some error'))),
217 })
218β
219 mutation.mutate()
220 await vi.advanceTimersByTimeAsync(10)
221β
222 mutation.reset()
223 expect(mutation).toMatchObject({
224 isIdle: { value: true },
225 isPending: { value: false },
226 isError: { value: false },
227 isSuccess: { value: false },
228 data: { value: undefined },
229 error: { value: null },
230 })
231 })
232β
233 describe('side effects', () => {
234 beforeEach(() => {
235 vi.clearAllMocks()
236 })
237β
238 it('should call onMutate when passed as an option', async () => {
239 const onMutate =
240 vi.fn<(variables: string, context: MutationFunctionContext) => void>()
241 const mutation = useMutation({
242 mutationFn: (params: string) => sleep(10).then(() => params),
243 onMutate,
244 })
245β
246 mutation.mutate('')
247 await vi.advanceTimersByTimeAsync(10)
248 expect(onMutate).toHaveBeenCalledTimes(1)
249 })
250β
251 it('should call onError when passed as an option', async () => {
252 const onError =
253 vi.fn<
254 (
255 error: Error,
256 variables: string,
257 onMutateResult: unknown,
258 context: MutationFunctionContext,
259 ) => void
260 >()
261 const mutation = useMutation({
262 mutationFn: () =>
263 sleep(10).then(() => Promise.reject(new Error('Some error'))),
264 onError,
265 })
266β
267 mutation.mutate('')
268 await vi.advanceTimersByTimeAsync(10)
269 expect(onError).toHaveBeenCalledTimes(1)
270 })
271β
272 it('should call onSuccess when passed as an option', async () => {
273 const onSuccess =
274 vi.fn<
275 (
276 data: string,
277 variables: string,
278 onMutateResult: unknown,
279 context: MutationFunctionContext,
280 ) => void
281 >()
282 const mutation = useMutation({
283 mutationFn: (params: string) => sleep(10).then(() => params),
284 onSuccess,
285 })
286β
287 mutation.mutate('')
288 await vi.advanceTimersByTimeAsync(10)
289 expect(onSuccess).toHaveBeenCalledTimes(1)
290 })
291β
292 it('should call onSettled when passed as an option', async () => {
293 const onSettled =
294 vi.fn<
295 (
296 data: string | undefined,
297 error: Error | null,
298 variables: string,
299 onMutateResult: unknown,
300 context: MutationFunctionContext,
301 ) => void
302 >()
303 const mutation = useMutation({
304 mutationFn: (params: string) => sleep(10).then(() => params),
305 onSettled,
306 })
307β
308 mutation.mutate('')
309 await vi.advanceTimersByTimeAsync(10)
310 expect(onSettled).toHaveBeenCalledTimes(1)
311 })
312β
313 it('should call onError when passed as an argument of mutate function', async () => {
314 const onError =
315 vi.fn<
316 (
317 error: Error,
318 variables: void,
319 onMutateResult: unknown,
320 context: MutationFunctionContext,
321 ) => void
322 >()
323 const mutation = useMutation({
324 mutationFn: () =>
325 sleep(10).then(() => Promise.reject(new Error('Some error'))),
326 })
327β
328 mutation.mutate(undefined, { onError })
329 await vi.advanceTimersByTimeAsync(10)
330 expect(onError).toHaveBeenCalledTimes(1)
331 })
332β
333 it('should call onSuccess when passed as an argument of mutate function', async () => {
334 const onSuccess =
335 vi.fn<
336 (
337 data: string,
338 variables: string,
339 onMutateResult: unknown,
340 context: MutationFunctionContext,
341 ) => void
342 >()
343 const mutation = useMutation({
344 mutationFn: (params: string) => sleep(10).then(() => params),
345 })
346β
347 mutation.mutate('', { onSuccess })
348 await vi.advanceTimersByTimeAsync(10)
349 expect(onSuccess).toHaveBeenCalledTimes(1)
350 })
351β
352 it('should call onSettled when passed as an argument of mutate function', async () => {
353 const onSettled =
354 vi.fn<
355 (
356 data: string | undefined,
357 error: Error | null,
358 variables: string,
359 onMutateResult: unknown,
360 context: MutationFunctionContext,
361 ) => void
362 >()
363 const mutation = useMutation({
364 mutationFn: (params: string) => sleep(10).then(() => params),
365 })
366β
367 mutation.mutate('', { onSettled })
368 await vi.advanceTimersByTimeAsync(10)
369 expect(onSettled).toHaveBeenCalledTimes(1)
370 })
371β
372 it('should call onSuccess and onSettled when passed as arguments of mutate function', async () => {
373 const callbacks: Array<string> = []
374 const mutation = useMutation({
375 mutationFn: (params: string) => sleep(10).then(() => params),
376 })
377β
378 mutation.mutate('', {
379 onSuccess: () => callbacks.push('mutate.onSuccess'),
380 onSettled: () => callbacks.push('mutate.onSettled'),
381 })
382 await vi.advanceTimersByTimeAsync(10)
383 expect(callbacks).toStrictEqual(['mutate.onSuccess', 'mutate.onSettled'])
384 })
385β
386 it('should call onError and onSettled when passed as arguments of mutate function', async () => {
387 const callbacks: Array<string> = []
388 const mutation = useMutation({
389 mutationFn: (_params: string) =>
390 sleep(10).then(() => Promise.reject(new Error('Some error'))),
391 })
392β
393 mutation.mutate('', {
394 onError: () => callbacks.push('mutate.onError'),
395 onSettled: () => callbacks.push('mutate.onSettled'),
396 })
397 await vi.advanceTimersByTimeAsync(10)
398 expect(callbacks).toStrictEqual(['mutate.onError', 'mutate.onSettled'])
399 })
400β
401 it('should call onSuccess and onSettled when passed as arguments of mutateAsync function', async () => {
402 const callbacks: Array<string> = []
403 const mutation = useMutation({
404 mutationFn: (params: string) => sleep(10).then(() => params),
405 })
406β
407 mutation.mutateAsync('', {
408 onSuccess: () => callbacks.push('mutateAsync.onSuccess'),
409 onSettled: () => callbacks.push('mutateAsync.onSettled'),
410 })
411 await vi.advanceTimersByTimeAsync(10)
412 expect(callbacks).toStrictEqual([
413 'mutateAsync.onSuccess',
414 'mutateAsync.onSettled',
415 ])
416 })
417β
418 it('should call onError and onSettled when passed as arguments of mutateAsync function', async () => {
419 const callbacks: Array<string> = []
420 const mutation = useMutation({
421 mutationFn: (_params: string) =>
422 sleep(10).then(() => Promise.reject(new Error('Some error'))),
423 })
424β
425 mutation
426 .mutateAsync('', {
427 onError: () => callbacks.push('mutateAsync.onError'),
428 onSettled: () => callbacks.push('mutateAsync.onSettled'),
429 })
430 .catch(noop)
431 await vi.advanceTimersByTimeAsync(10)
432 expect(callbacks).toStrictEqual([
433 'mutateAsync.onError',
434 'mutateAsync.onSettled',
435 ])
436 })
437β
438 it('should call onSuccess when passed as an argument of mutateAsync function', async () => {
439 const callbacks: Array<string> = []
440 const mutation = useMutation({
441 mutationFn: (params: string) => sleep(10).then(() => params),
442 })
443β
444 mutation.mutateAsync('', {
445 onSuccess: () => callbacks.push('mutateAsync.onSuccess'),
446 })
447 await vi.advanceTimersByTimeAsync(10)
448 expect(callbacks).toStrictEqual(['mutateAsync.onSuccess'])
449 })
450β
451 it('should call onError when passed as an argument of mutateAsync function', async () => {
452 const callbacks: Array<string> = []
453 const mutation = useMutation({
454 mutationFn: (_params: string) =>
455 sleep(10).then(() => Promise.reject(new Error('Some error'))),
456 })
457β
458 mutation
459 .mutateAsync('', {
460 onError: () => callbacks.push('mutateAsync.onError'),
461 })
462 .catch(noop)
463 await vi.advanceTimersByTimeAsync(10)
464 expect(callbacks).toStrictEqual(['mutateAsync.onError'])
465 })
466β
467 it('should call onSettled when passed as an argument of mutateAsync function', async () => {
468 const callbacks: Array<string> = []
469 const mutation = useMutation({
470 mutationFn: (params: string) => sleep(10).then(() => params),
471 })
472β
473 mutation.mutateAsync('', {
474 onSettled: () => callbacks.push('mutateAsync.onSettled'),
475 })
476 await vi.advanceTimersByTimeAsync(10)
477 expect(callbacks).toStrictEqual(['mutateAsync.onSettled'])
478 })
479β
480 it('should fire both onSettled functions', async () => {
481 const onSettled =
482 vi.fn<
483 (
484 data: string | undefined,
485 error: Error | null,
486 variables: string,
487 onMutateResult: unknown,
488 context: MutationFunctionContext,
489 ) => void
490 >()
491 const onSettledMutate =
492 vi.fn<
493 (
494 data: string | undefined,
495 error: Error | null,
496 variables: string,
497 onMutateResult: unknown,
498 context: MutationFunctionContext,
499 ) => void
500 >()
501 const mutation = useMutation({
502 mutationFn: (params: string) => sleep(10).then(() => params),
503 onSettled,
504 })
505β
506 mutation.mutate('', { onSettled: onSettledMutate })
507 await vi.advanceTimersByTimeAsync(10)
508 expect(onSettled).toHaveBeenCalledTimes(1)
509 expect(onSettledMutate).toHaveBeenCalledTimes(1)
510 })
511 })
512β
513 describe('async', () => {
514 beforeEach(() => {
515 vi.clearAllMocks()
516 })
517β
518 it('should resolve properly', async () => {
519 const result = 'Mock data'
520 const mutation = useMutation({
521 mutationFn: (params: string) => sleep(10).then(() => params),
522 })
523β
524 const promise = mutation.mutateAsync(result)
525β
526 await vi.advanceTimersByTimeAsync(10)
527 await expect(promise).resolves.toBe(result)
528β
529 expect(mutation).toMatchObject({
530 isIdle: { value: false },
531 isPending: { value: false },
532 isError: { value: false },
533 isSuccess: { value: true },
534 data: { value: 'Mock data' },
535 error: { value: null },
536 })
537 })
538β
539 it('should throw on error', async () => {
540 const mutation = useMutation({
541 mutationFn: () =>
542 sleep(10).then(() => Promise.reject(new Error('Some error'))),
543 })
544β
545 await Promise.all([
546 expect(mutation.mutateAsync()).rejects.toThrow('Some error'),
547 vi.advanceTimersByTimeAsync(10),
548 ])
549 expect(mutation).toMatchObject({
550 isIdle: { value: false },
551 isPending: { value: false },
552 isError: { value: true },
553 isSuccess: { value: false },
554 data: { value: undefined },
555 error: { value: Error('Some error') },
556 })
557 })
558 })
559β
560 it('should stop listening to changes on onScopeDispose', async () => {
561 const key = createKey()
562 const queryClient = useQueryClient()
563 const onScopeDisposeMock = vi.mocked(onScopeDispose)
564 onScopeDisposeMock.mockImplementationOnce((fn) => fn())
565β
566 const mutation = useMutation({
567 mutationKey: key,
568 mutationFn: (params: string) => sleep(10).then(() => params),
569 })
570β
571 expect(mutation.status.value).toBe('idle')
572β
573 mutation.mutate('a')
574 await vi.advanceTimersByTimeAsync(0)
575 expect(queryClient.isMutating({ mutationKey: key })).toBe(1)
576 expect(mutation.status.value).toBe('idle')
577 await vi.advanceTimersByTimeAsync(10)
578 expect(queryClient.isMutating({ mutationKey: key })).toBe(0)
579 expect(mutation.status.value).toBe('idle')
580 })
581β
582 it.runIf(isVue3)(
583 'should return deeply reactive and readonly data by default',
584 async () => {
585 const { mutate, data } = useMutation({
586 mutationFn: () => sleep(10).then(() => ({ nested: { count: 0 } })),
587 })
588β
589 mutate()
590 await vi.advanceTimersByTimeAsync(10)
591 expect(data.value).toStrictEqual({ nested: { count: 0 } })
592 expect(isReactive(data.value?.nested)).toBe(true)
593 expect(isReadonly(data.value?.nested)).toBe(true)
594 },
595 )
596β
597 it('should return data in a shallow ref when shallow is true', async () => {
598 const { mutate, data } = useMutation({
599 mutationFn: () => sleep(10).then(() => ({ nested: { count: 0 } })),
600 shallow: true,
601 })
602β
603 mutate()
604 await vi.advanceTimersByTimeAsync(10)
605 expect(data.value).toStrictEqual({ nested: { count: 0 } })
606 expect(isReactive(data.value?.nested)).toBe(false)
607 expect(isReadonly(data.value?.nested)).toBe(false)
608 })
609β
610 it('should warn when used outside of setup function in development mode', () => {
611 vi.stubEnv('NODE_ENV', 'development')
612 const consoleWarnMock = vi
613 .spyOn(console, 'warn')
614 .mockImplementation(() => {})
615β
616 useMutation({
617 mutationFn: (params: string) => sleep(0).then(() => params),
618 })
619β
620 expect(consoleWarnMock).toHaveBeenCalledWith(
621 'vue-query composable like "useQuery()" should only be used inside a "setup()" function or a running effect scope. They might otherwise lead to memory leaks.',
622 )
623 })
624β
625 describe('throwOnError', () => {
626 it('should evaluate throwOnError when mutation is expected to throw', async () => {
627 const err = new Error('Expected mock error. All is well!')
628 const throwOnError = vi.fn<(error: Error) => boolean>()
629 const { mutate } = useMutation({
630 mutationFn: () => sleep(10).then(() => Promise.reject(err)),
631 throwOnError,
632 })
633β
634 mutate()
635 await vi.advanceTimersByTimeAsync(10)
636 expect(throwOnError).toHaveBeenCalledTimes(1)
637 expect(throwOnError).toHaveBeenCalledWith(err)
638 })
639β
640 it.runIf(isVue2)(
641 'should throw from error watcher when throwOnError returns true, which Vue 2 logs via console.error',
642 async () => {
643 const consoleErrorMock = vi
644 .spyOn(console, 'error')
645 .mockReturnValue(undefined)
646 const throwOnError = vi.fn<() => boolean>().mockReturnValue(true)
647 const { mutate } = useMutation({
648 mutationFn: () =>
649 sleep(10).then(() => Promise.reject(new Error('Some error'))),
650 throwOnError,
651 })
652β
653 mutate()
654 await vi.advanceTimersByTimeAsync(10)
655 expect(throwOnError).toHaveBeenCalledTimes(1)
656 expect(throwOnError).toHaveBeenCalledWith(Error('Some error'))
657 expect(consoleErrorMock).toHaveBeenCalledWith(Error('Some error'))
658 },
659 )
660β
661 it.runIf(isVue3)(
662 'should throw from error watcher when throwOnError returns true, which Vue 3 surfaces as an unhandled rejection',
663 async ({ onTestFinished }) => {
664 const throwOnError = vi.fn<() => boolean>().mockReturnValue(true)
665 const { mutate } = useMutation({
666 mutationFn: () =>
667 sleep(10).then(() => Promise.reject(new Error('Some error'))),
668 throwOnError,
669 })
670β
671 const unhandledRejectionFn = vi.fn<NodeJS.UnhandledRejectionListener>()
672 process.on('unhandledRejection', unhandledRejectionFn)
673 onTestFinished(() => {
674 process.off('unhandledRejection', unhandledRejectionFn)
675 })
676β
677 mutate()
678 await vi.advanceTimersByTimeAsync(10)
679 expect(throwOnError).toHaveBeenCalledTimes(1)
680 expect(throwOnError).toHaveBeenCalledWith(Error('Some error'))
681 expect(unhandledRejectionFn).toHaveBeenCalledTimes(1)
682 expect(unhandledRejectionFn).toHaveBeenCalledWith(
683 Error('Some error'),
684 expect.any(Promise),
685 )
686 },
687 )
688 })
689β
690 describe('optimistic updates', () => {
691 it('should update the cache in onMutate and roll back via onMutateResult in onError', async () => {
692 const key = createKey()
693 const queryClient = useQueryClient()
694 queryClient.setQueryData<Array<string>>(key, ['Todo 1'])
695β
696 const mutation = useMutation({
697 mutationFn: () =>
698 sleep(10).then(() => Promise.reject(new Error('Some error'))),
699 onMutate: async (newTodo: string) => {
700 await queryClient.cancelQueries({ queryKey: key })
701 const previousTodos = queryClient.getQueryData<Array<string>>(key)
702β
703 queryClient.setQueryData<Array<string>>(key, (old) => [
704 ...(old ?? []),
705 newTodo,
706 ])
707β
708 return { previousTodos }
709 },
710 onError: (_err, _newTodo, onMutateResult) => {
711 queryClient.setQueryData(key, onMutateResult?.previousTodos)
712 },
713 })
714β
715 mutation.mutate('Todo 2')
716β
717 // onMutate runs synchronously up to its first await, so the optimistic
718 // value is visible immediately, before the mutationFn settles.
719 await vi.advanceTimersByTimeAsync(0)
720 expect(queryClient.getQueryData(key)).toStrictEqual(['Todo 1', 'Todo 2'])
721 await vi.advanceTimersByTimeAsync(10)
722 expect(mutation).toMatchObject({ isError: { value: true } })
723 expect(queryClient.getQueryData(key)).toStrictEqual(['Todo 1'])
724 })
725β
726 it('should keep the optimistic update in place when the mutation succeeds', async () => {
727 const key = createKey()
728 const queryClient = useQueryClient()
729 queryClient.setQueryData<Array<string>>(key, ['Todo 1'])
730β
731 const mutation = useMutation({
732 mutationFn: (newTodo: string) => sleep(10).then(() => newTodo),
733 onMutate: async (newTodo: string) => {
734 await queryClient.cancelQueries({ queryKey: key })
735 const previousTodos = queryClient.getQueryData<Array<string>>(key)
736β
737 queryClient.setQueryData<Array<string>>(key, (old) => [
738 ...(old ?? []),
739 newTodo,
740 ])
741β
742 return { previousTodos }
743 },
744 onError: (_err, _newTodo, onMutateResult) => {
745 queryClient.setQueryData(key, onMutateResult?.previousTodos)
746 },
747 })
748β
749 mutation.mutate('Todo 2')
750 await vi.advanceTimersByTimeAsync(10)
751 expect(mutation).toMatchObject({ isSuccess: { value: true } })
752 expect(queryClient.getQueryData(key)).toStrictEqual(['Todo 1', 'Todo 2'])
753 })
754 })
755β
756 describe('concurrent mutate calls', () => {
757 it('should report each call result independently when some fail', async () => {
758 const mutation = useMutation({
759 mutationFn: (todo: string) =>
760 todo === 'bad'
761 ? sleep(10).then(() => Promise.reject(new Error('Some error')))
762 : sleep(10).then(() => todo),
763 })
764β
765 const todos = ['Todo 1', 'bad', 'Todo 3']
766β
767 const settledPromise = Promise.allSettled(
768 todos.map((todo) => mutation.mutateAsync(todo)),
769 )
770 await vi.advanceTimersByTimeAsync(10)
771 const results = await settledPromise
772 expect(results).toStrictEqual([
773 { status: 'fulfilled', value: 'Todo 1' },
774 { status: 'rejected', reason: Error('Some error') },
775 { status: 'fulfilled', value: 'Todo 3' },
776 ])
777 })
778β
779 it('should only fire the per-call onSuccess for the last mutate() call', async () => {
780 const onSuccessMutate =
781 vi.fn<
782 (
783 data: string,
784 variables: string,
785 onMutateResult: unknown,
786 context: MutationFunctionContext,
787 ) => void
788 >()
789 const mutation = useMutation({
790 mutationFn: (todo: string) => sleep(10).then(() => todo),
791 })
792β
793 mutation.mutate('Todo 1', { onSuccess: onSuccessMutate })
794 mutation.mutate('Todo 2', { onSuccess: onSuccessMutate })
795 await vi.advanceTimersByTimeAsync(10)
796 expect(onSuccessMutate).toHaveBeenCalledTimes(1)
797 const [data, variables, onMutateResult, context] =
798 onSuccessMutate.mock.calls[0]!
799 expect(data).toBe('Todo 2')
800 expect(variables).toBe('Todo 2')
801 expect(onMutateResult).toBeUndefined()
802 expect(context.client).toBe(useQueryClient())
803 })
804 })
805β
806 it('should pass a non-undefined onMutateResult alongside context to onSuccess', async () => {
807 const onSuccess =
808 vi.fn<
809 (
810 data: string,
811 variables: string,
812 onMutateResult: { startedWith: string },
813 context: MutationFunctionContext,
814 ) => void
815 >()
816 const mutation = useMutation({
817 mutationFn: (text: string) => sleep(10).then(() => text.toUpperCase()),
818 onMutate: (text: string) => ({ startedWith: text }),
819 onSuccess,
820 })
821β
822 mutation.mutate('todo')
823 await vi.advanceTimersByTimeAsync(10)
824 expect(onSuccess).toHaveBeenCalledTimes(1)
825 const [data, variables, onMutateResult, context] = onSuccess.mock.calls[0]!
826 expect(data).toBe('TODO')
827 expect(variables).toBe('todo')
828 expect(onMutateResult).toStrictEqual({ startedWith: 'todo' })
829 expect(context.client).toBe(useQueryClient())
830 expect(context.meta).toBeUndefined()
831 expect(context.mutationKey).toBeUndefined()
832 })
833β
834 it('should give mutationFn the same QueryClient instance via context', async () => {
835 const key = createKey()
836 const queryClient = useQueryClient()
837 queryClient.setQueryData(key, 'tag-from-this-client')
838β
839 const mutation = useMutation({
840 mutationFn: (_text: string, context: MutationFunctionContext) =>
841 sleep(10).then(() => context.client.getQueryData(key)),
842 })
843β
844 mutation.mutate('todo')
845 await vi.advanceTimersByTimeAsync(10)
846 expect(mutation.data.value).toBe('tag-from-this-client')
847 })
848β
849 it('should include mutationKey in the context passed to hook-level callbacks', async () => {
850 const onSuccess =
851 vi.fn<
852 (
853 data: string,
854 variables: string,
855 onMutateResult: unknown,
856 context: MutationFunctionContext,
857 ) => void
858 >()
859 const mutation = useMutation({
860 mutationKey: ['todos', 'add'],
861 mutationFn: (text: string) => sleep(10).then(() => text),
862 onSuccess,
863 })
864β
865 mutation.mutate('todo')
866 await vi.advanceTimersByTimeAsync(10)
867 expect(onSuccess).toHaveBeenCalledTimes(1)
868 expect(onSuccess.mock.calls[0]?.[3].mutationKey).toStrictEqual([
869 'todos',
870 'add',
871 ])
872 })
873β
874 it('should let onSuccess invalidate queries via context.client without a useQueryClient() closure', async () => {
875 const key = createKey()
876 const queryClient = useQueryClient()
877 queryClient.setQueryData(key, 'data')
878β
879 const mutation = useMutation({
880 mutationFn: () => sleep(10).then(() => 'mutated'),
881 onSuccess: (_data, _variables, _onMutateResult, context) => {
882 context.client.invalidateQueries({ queryKey: key })
883 },
884 })
885β
886 expect(queryClient.getQueryState(key)?.isInvalidated).toBe(false)
887β
888 mutation.mutate()
889 await vi.advanceTimersByTimeAsync(10)
890 expect(queryClient.getQueryState(key)?.isInvalidated).toBe(true)
891 })
892})