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