Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

useMutation.test.ts

771 lines23.1 KB

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