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