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

useMutation.test.tsx

1,143 lines30.0 KB

1import { describe, expect, it, vi } from 'vitest'
2import { fireEvent, render, waitFor } from '@testing-library/react'
3import * as React from 'react'
4import { ErrorBoundary } from 'react-error-boundary'
5import { MutationCache, QueryCache, useMutation } from '..'
6import {
7 createQueryClient,
8 mockOnlineManagerIsOnline,
9 queryKey,
10 renderWithClient,
11 setActTimeout,
12 sleep,
13} from './utils'
14import type { UseMutationResult } from '../types'
15​
16describe('useMutation', () => {
17 const queryCache = new QueryCache()
18 const mutationCache = new MutationCache()
19 const queryClient = createQueryClient({ queryCache, mutationCache })
20​
21 it('should be able to reset `data`', async () => {
22 function Page() {
23 const {
24 mutate,
25 data = 'empty',
26 reset,
27 } = useMutation({ mutationFn: () => Promise.resolve('mutation') })
28​
29 return (
30 <div>
31 <h1>{data}</h1>
32 <button onClick={() => reset()}>reset</button>
33 <button onClick={() => mutate()}>mutate</button>
34 </div>
35 )
36 }
37​
38 const { getByRole } = renderWithClient(queryClient, <Page />)
39​
40 expect(getByRole('heading').textContent).toBe('empty')
41​
42 fireEvent.click(getByRole('button', { name: /mutate/i }))
43​
44 await waitFor(() => {
45 expect(getByRole('heading').textContent).toBe('mutation')
46 })
47​
48 fireEvent.click(getByRole('button', { name: /reset/i }))
49​
50 await waitFor(() => {
51 expect(getByRole('heading').textContent).toBe('empty')
52 })
53 })
54​
55 it('should be able to reset `error`', async () => {
56 function Page() {
57 const { mutate, error, reset } = useMutation<string, Error>({
58 mutationFn: () => {
59 const err = new Error('Expected mock error. All is well!')
60 err.stack = ''
61 return Promise.reject(err)
62 },
63 })
64​
65 return (
66 <div>
67 {error && <h1>{error.message}</h1>}
68 <button onClick={() => reset()}>reset</button>
69 <button onClick={() => mutate()}>mutate</button>
70 </div>
71 )
72 }
73​
74 const { getByRole, queryByRole } = renderWithClient(queryClient, <Page />)
75​
76 await waitFor(() => {
77 expect(queryByRole('heading')).toBeNull()
78 })
79​
80 fireEvent.click(getByRole('button', { name: /mutate/i }))
81​
82 await waitFor(() => {
83 expect(getByRole('heading').textContent).toBe(
84 'Expected mock error. All is well!',
85 )
86 })
87​
88 fireEvent.click(getByRole('button', { name: /reset/i }))
89​
90 await waitFor(() => {
91 expect(queryByRole('heading')).toBeNull()
92 })
93 })
94​
95 it('should be able to call `onSuccess` and `onSettled` after each successful mutate', async () => {
96 let count = 0
97 const onSuccessMock = vi.fn()
98 const onSettledMock = vi.fn()
99​
100 function Page() {
101 const { mutate } = useMutation({
102 mutationFn: (vars: { count: number }) => Promise.resolve(vars.count),
103​
104 onSuccess: (data) => {
105 onSuccessMock(data)
106 },
107 onSettled: (data) => {
108 onSettledMock(data)
109 },
110 })
111​
112 return (
113 <div>
114 <h1>{count}</h1>
115 <button onClick={() => mutate({ count: ++count })}>mutate</button>
116 </div>
117 )
118 }
119​
120 const { getByRole } = renderWithClient(queryClient, <Page />)
121​
122 expect(getByRole('heading').textContent).toBe('0')
123​
124 fireEvent.click(getByRole('button', { name: /mutate/i }))
125 fireEvent.click(getByRole('button', { name: /mutate/i }))
126 fireEvent.click(getByRole('button', { name: /mutate/i }))
127​
128 await waitFor(() => {
129 expect(getByRole('heading').textContent).toBe('3')
130 })
131​
132 await waitFor(() => {
133 expect(onSuccessMock).toHaveBeenCalledTimes(3)
134 })
135​
136 expect(onSuccessMock).toHaveBeenCalledWith(1)
137 expect(onSuccessMock).toHaveBeenCalledWith(2)
138 expect(onSuccessMock).toHaveBeenCalledWith(3)
139​
140 await waitFor(() => {
141 expect(onSettledMock).toHaveBeenCalledTimes(3)
142 })
143​
144 expect(onSettledMock).toHaveBeenCalledWith(1)
145 expect(onSettledMock).toHaveBeenCalledWith(2)
146 expect(onSettledMock).toHaveBeenCalledWith(3)
147 })
148​
149 it('should set correct values for `failureReason` and `failureCount` on multiple mutate calls', async () => {
150 let count = 0
151 type Value = { count: number }
152​
153 const mutateFn = vi.fn<[value: Value], Promise<Value>>()
154​
155 mutateFn.mockImplementationOnce(() => {
156 return Promise.reject(new Error('Error test Jonas'))
157 })
158​
159 mutateFn.mockImplementation(async (value) => {
160 await sleep(10)
161 return Promise.resolve(value)
162 })
163​
164 function Page() {
165 const { mutate, failureCount, failureReason, data, status } = useMutation(
166 { mutationFn: mutateFn },
167 )
168​
169 return (
170 <div>
171 <h1>Data {data?.count}</h1>
172 <h2>Status {status}</h2>
173 <h2>Failed {failureCount} times</h2>
174 <h2>Failed because {failureReason?.message ?? 'null'}</h2>
175 <button onClick={() => mutate({ count: ++count })}>mutate</button>
176 </div>
177 )
178 }
179​
180 const rendered = renderWithClient(queryClient, <Page />)
181​
182 await waitFor(() => rendered.getByText('Data'))
183​
184 fireEvent.click(rendered.getByRole('button', { name: /mutate/i }))
185 await waitFor(() => rendered.getByText('Data'))
186 await waitFor(() => rendered.getByText('Status error'))
187 await waitFor(() => rendered.getByText('Failed 1 times'))
188 await waitFor(() => rendered.getByText('Failed because Error test Jonas'))
189​
190 fireEvent.click(rendered.getByRole('button', { name: /mutate/i }))
191 await waitFor(() => rendered.getByText('Status pending'))
192 await waitFor(() => rendered.getByText('Status success'))
193 await waitFor(() => rendered.getByText('Data 2'))
194 await waitFor(() => rendered.getByText('Failed 0 times'))
195 await waitFor(() => rendered.getByText('Failed because null'))
196 })
197​
198 it('should be able to call `onError` and `onSettled` after each failed mutate', async () => {
199 const onErrorMock = vi.fn()
200 const onSettledMock = vi.fn()
201 let count = 0
202​
203 function Page() {
204 const { mutate } = useMutation({
205 mutationFn: (vars: { count: number }) => {
206 const error = new Error(
207 `Expected mock error. All is well! ${vars.count}`,
208 )
209 error.stack = ''
210 return Promise.reject(error)
211 },
212 onError: (error: Error) => {
213 onErrorMock(error.message)
214 },
215 onSettled: (_data, error) => {
216 onSettledMock(error?.message)
217 },
218 })
219​
220 return (
221 <div>
222 <h1>{count}</h1>
223 <button onClick={() => mutate({ count: ++count })}>mutate</button>
224 </div>
225 )
226 }
227​
228 const { getByRole } = renderWithClient(queryClient, <Page />)
229​
230 expect(getByRole('heading').textContent).toBe('0')
231​
232 fireEvent.click(getByRole('button', { name: /mutate/i }))
233 fireEvent.click(getByRole('button', { name: /mutate/i }))
234 fireEvent.click(getByRole('button', { name: /mutate/i }))
235​
236 await waitFor(() => {
237 expect(getByRole('heading').textContent).toBe('3')
238 })
239​
240 await waitFor(() => {
241 expect(onErrorMock).toHaveBeenCalledTimes(3)
242 })
243 expect(onErrorMock).toHaveBeenCalledWith(
244 'Expected mock error. All is well! 1',
245 )
246 expect(onErrorMock).toHaveBeenCalledWith(
247 'Expected mock error. All is well! 2',
248 )
249 expect(onErrorMock).toHaveBeenCalledWith(
250 'Expected mock error. All is well! 3',
251 )
252​
253 await waitFor(() => {
254 expect(onSettledMock).toHaveBeenCalledTimes(3)
255 })
256 expect(onSettledMock).toHaveBeenCalledWith(
257 'Expected mock error. All is well! 1',
258 )
259 expect(onSettledMock).toHaveBeenCalledWith(
260 'Expected mock error. All is well! 2',
261 )
262 expect(onSettledMock).toHaveBeenCalledWith(
263 'Expected mock error. All is well! 3',
264 )
265 })
266​
267 it('should be able to override the useMutation success callbacks', async () => {
268 const callbacks: Array<string> = []
269​
270 function Page() {
271 const { mutateAsync } = useMutation({
272 mutationFn: async (text: string) => text,
273 onSuccess: async () => {
274 callbacks.push('useMutation.onSuccess')
275 },
276 onSettled: async () => {
277 callbacks.push('useMutation.onSettled')
278 },
279 })
280​
281 React.useEffect(() => {
282 setActTimeout(async () => {
283 try {
284 const result = await mutateAsync('todo', {
285 onSuccess: async () => {
286 callbacks.push('mutateAsync.onSuccess')
287 },
288 onSettled: async () => {
289 callbacks.push('mutateAsync.onSettled')
290 },
291 })
292 callbacks.push(`mutateAsync.result:${result}`)
293 } catch {}
294 }, 10)
295 }, [mutateAsync])
296​
297 return null
298 }
299​
300 renderWithClient(queryClient, <Page />)
301​
302 await sleep(100)
303​
304 expect(callbacks).toEqual([
305 'useMutation.onSuccess',
306 'useMutation.onSettled',
307 'mutateAsync.onSuccess',
308 'mutateAsync.onSettled',
309 'mutateAsync.result:todo',
310 ])
311 })
312​
313 it('should be able to override the error callbacks when using mutateAsync', async () => {
314 const callbacks: Array<string> = []
315​
316 function Page() {
317 const { mutateAsync } = useMutation({
318 mutationFn: async (_text: string) => Promise.reject(new Error('oops')),
319 onError: async () => {
320 callbacks.push('useMutation.onError')
321 },
322 onSettled: async () => {
323 callbacks.push('useMutation.onSettled')
324 },
325 })
326​
327 React.useEffect(() => {
328 setActTimeout(async () => {
329 try {
330 await mutateAsync('todo', {
331 onError: async () => {
332 callbacks.push('mutateAsync.onError')
333 },
334 onSettled: async () => {
335 callbacks.push('mutateAsync.onSettled')
336 },
337 })
338 } catch (error) {
339 callbacks.push(`mutateAsync.error:${(error as Error).message}`)
340 }
341 }, 10)
342 }, [mutateAsync])
343​
344 return null
345 }
346​
347 renderWithClient(queryClient, <Page />)
348​
349 await sleep(100)
350​
351 expect(callbacks).toEqual([
352 'useMutation.onError',
353 'useMutation.onSettled',
354 'mutateAsync.onError',
355 'mutateAsync.onSettled',
356 'mutateAsync.error:oops',
357 ])
358 })
359​
360 it('should be able to use mutation defaults', async () => {
361 const key = queryKey()
362​
363 queryClient.setMutationDefaults(key, {
364 mutationFn: async (text: string) => {
365 await sleep(10)
366 return text
367 },
368 })
369​
370 const states: Array<UseMutationResult<any, any, any, any>> = []
371​
372 function Page() {
373 const state = useMutation<string, unknown, string>({ mutationKey: key })
374​
375 states.push(state)
376​
377 const { mutate } = state
378​
379 React.useEffect(() => {
380 setActTimeout(() => {
381 mutate('todo')
382 }, 10)
383 }, [mutate])
384​
385 return null
386 }
387​
388 renderWithClient(queryClient, <Page />)
389​
390 await sleep(100)
391​
392 expect(states.length).toBe(3)
393 expect(states[0]).toMatchObject({ data: undefined, isPending: false })
394 expect(states[1]).toMatchObject({ data: undefined, isPending: true })
395 expect(states[2]).toMatchObject({ data: 'todo', isPending: false })
396 })
397​
398 it('should be able to retry a failed mutation', async () => {
399 let count = 0
400​
401 function Page() {
402 const { mutate } = useMutation({
403 mutationFn: (_text: string) => {
404 count++
405 return Promise.reject(new Error('oops'))
406 },
407 retry: 1,
408 retryDelay: 5,
409 })
410​
411 React.useEffect(() => {
412 setActTimeout(() => {
413 mutate('todo')
414 }, 10)
415 }, [mutate])
416​
417 return null
418 }
419​
420 renderWithClient(queryClient, <Page />)
421​
422 await sleep(100)
423​
424 expect(count).toBe(2)
425 })
426​
427 it('should not retry mutations while offline', async () => {
428 const onlineMock = mockOnlineManagerIsOnline(false)
429​
430 let count = 0
431​
432 function Page() {
433 const mutation = useMutation({
434 mutationFn: (_text: string) => {
435 count++
436 return Promise.reject(new Error('oops'))
437 },
438 retry: 1,
439 retryDelay: 5,
440 })
441​
442 return (
443 <div>
444 <button onClick={() => mutation.mutate('todo')}>mutate</button>
445 <div>
446 error:{' '}
447 {mutation.error instanceof Error ? mutation.error.message : 'null'},
448 status: {mutation.status}, isPaused: {String(mutation.isPaused)}
449 </div>
450 </div>
451 )
452 }
453​
454 const rendered = renderWithClient(queryClient, <Page />)
455​
456 window.dispatchEvent(new Event('offline'))
457​
458 await waitFor(() => {
459 expect(
460 rendered.getByText('error: null, status: idle, isPaused: false'),
461 ).toBeInTheDocument()
462 })
463​
464 fireEvent.click(rendered.getByRole('button', { name: /mutate/i }))
465​
466 await waitFor(() => {
467 expect(
468 rendered.getByText('error: null, status: pending, isPaused: true'),
469 ).toBeInTheDocument()
470 })
471​
472 expect(count).toBe(0)
473​
474 onlineMock.mockRestore()
475 window.dispatchEvent(new Event('online'))
476​
477 await sleep(100)
478​
479 await waitFor(() => {
480 expect(
481 rendered.getByText('error: oops, status: error, isPaused: false'),
482 ).toBeInTheDocument()
483 })
484​
485 expect(count).toBe(2)
486 })
487​
488 it('should call onMutate even if paused', async () => {
489 const onlineMock = mockOnlineManagerIsOnline(false)
490 const onMutate = vi.fn()
491 let count = 0
492​
493 function Page() {
494 const mutation = useMutation({
495 mutationFn: async (_text: string) => {
496 count++
497 await sleep(10)
498 return count
499 },
500 onMutate,
501 })
502​
503 return (
504 <div>
505 <button onClick={() => mutation.mutate('todo')}>mutate</button>
506 <div>
507 data: {mutation.data ?? 'null'}, status: {mutation.status},
508 isPaused: {String(mutation.isPaused)}
509 </div>
510 </div>
511 )
512 }
513​
514 const rendered = renderWithClient(queryClient, <Page />)
515​
516 await rendered.findByText('data: null, status: idle, isPaused: false')
517​
518 window.dispatchEvent(new Event('offline'))
519​
520 fireEvent.click(rendered.getByRole('button', { name: /mutate/i }))
521​
522 await rendered.findByText('data: null, status: pending, isPaused: true')
523​
524 expect(onMutate).toHaveBeenCalledTimes(1)
525 expect(onMutate).toHaveBeenCalledWith('todo')
526​
527 onlineMock.mockRestore()
528 window.dispatchEvent(new Event('online'))
529​
530 await rendered.findByText('data: 1, status: success, isPaused: false')
531​
532 expect(onMutate).toHaveBeenCalledTimes(1)
533 expect(count).toBe(1)
534 })
535​
536 it('should optimistically go to paused state if offline', async () => {
537 const onlineMock = mockOnlineManagerIsOnline(false)
538 let count = 0
539 const states: Array<string> = []
540​
541 function Page() {
542 const mutation = useMutation({
543 mutationFn: async (_text: string) => {
544 count++
545 await sleep(10)
546 return count
547 },
548 })
549​
550 states.push(`${mutation.status}, ${mutation.isPaused}`)
551​
552 return (
553 <div>
554 <button onClick={() => mutation.mutate('todo')}>mutate</button>
555 <div>
556 data: {mutation.data ?? 'null'}, status: {mutation.status},
557 isPaused: {String(mutation.isPaused)}
558 </div>
559 </div>
560 )
561 }
562​
563 const rendered = renderWithClient(queryClient, <Page />)
564​
565 await rendered.findByText('data: null, status: idle, isPaused: false')
566​
567 window.dispatchEvent(new Event('offline'))
568​
569 fireEvent.click(rendered.getByRole('button', { name: /mutate/i }))
570​
571 await rendered.findByText('data: null, status: pending, isPaused: true')
572​
573 // no intermediate 'pending, false' state is expected because we don't start mutating!
574 expect(states[0]).toBe('idle, false')
575 expect(states[1]).toBe('pending, true')
576​
577 onlineMock.mockRestore()
578 window.dispatchEvent(new Event('online'))
579​
580 await rendered.findByText('data: 1, status: success, isPaused: false')
581 })
582​
583 it('should be able to retry a mutation when online', async () => {
584 const onlineMock = mockOnlineManagerIsOnline(false)
585​
586 let count = 0
587 const states: Array<UseMutationResult<any, any, any, any>> = []
588​
589 function Page() {
590 const state = useMutation({
591 mutationFn: async (_text: string) => {
592 await sleep(1)
593 count++
594 return count > 1
595 ? Promise.resolve('data')
596 : Promise.reject(new Error('oops'))
597 },
598 retry: 1,
599 retryDelay: 5,
600 networkMode: 'offlineFirst',
601 })
602​
603 states.push(state)
604​
605 const { mutate } = state
606​
607 React.useEffect(() => {
608 setActTimeout(() => {
609 window.dispatchEvent(new Event('offline'))
610 mutate('todo')
611 }, 10)
612 }, [mutate])
613​
614 return null
615 }
616​
617 renderWithClient(queryClient, <Page />)
618​
619 await sleep(50)
620​
621 expect(states.length).toBe(4)
622 expect(states[0]).toMatchObject({
623 isPending: false,
624 isPaused: false,
625 failureCount: 0,
626 failureReason: null,
627 })
628 expect(states[1]).toMatchObject({
629 isPending: true,
630 isPaused: false,
631 failureCount: 0,
632 failureReason: null,
633 })
634 expect(states[2]).toMatchObject({
635 isPending: true,
636 isPaused: false,
637 failureCount: 1,
638 failureReason: new Error('oops'),
639 })
640 expect(states[3]).toMatchObject({
641 isPending: true,
642 isPaused: true,
643 failureCount: 1,
644 failureReason: new Error('oops'),
645 })
646​
647 onlineMock.mockRestore()
648 window.dispatchEvent(new Event('online'))
649​
650 await sleep(50)
651​
652 expect(states.length).toBe(6)
653 expect(states[4]).toMatchObject({
654 isPending: true,
655 isPaused: false,
656 failureCount: 1,
657 failureReason: new Error('oops'),
658 })
659 expect(states[5]).toMatchObject({
660 isPending: false,
661 isPaused: false,
662 failureCount: 0,
663 failureReason: null,
664 data: 'data',
665 })
666 })
667​
668 it('should not change state if unmounted', async () => {
669 function Mutates() {
670 const { mutate } = useMutation({ mutationFn: () => sleep(10) })
671 return <button onClick={() => mutate()}>mutate</button>
672 }
673 function Page() {
674 const [mounted, setMounted] = React.useState(true)
675 return (
676 <div>
677 <button onClick={() => setMounted(false)}>unmount</button>
678 {mounted && <Mutates />}
679 </div>
680 )
681 }
682​
683 const { getByText } = renderWithClient(queryClient, <Page />)
684 fireEvent.click(getByText('mutate'))
685 fireEvent.click(getByText('unmount'))
686 })
687​
688 it('should be able to throw an error when throwOnError is set to true', async () => {
689 const consoleMock = vi
690 .spyOn(console, 'error')
691 .mockImplementation(() => undefined)
692 function Page() {
693 const { mutate } = useMutation<string, Error>({
694 mutationFn: () => {
695 const err = new Error('Expected mock error. All is well!')
696 err.stack = ''
697 return Promise.reject(err)
698 },
699 throwOnError: true,
700 })
701​
702 return (
703 <div>
704 <button onClick={() => mutate()}>mutate</button>
705 </div>
706 )
707 }
708​
709 const { getByText, queryByText } = renderWithClient(
710 queryClient,
711 <ErrorBoundary
712 fallbackRender={() => (
713 <div>
714 <span>error</span>
715 </div>
716 )}
717 >
718 <Page />
719 </ErrorBoundary>,
720 )
721​
722 fireEvent.click(getByText('mutate'))
723​
724 await waitFor(() => {
725 expect(queryByText('error')).not.toBeNull()
726 })
727​
728 expect(consoleMock).toHaveBeenCalledWith(
729 expect.objectContaining(new Error('Expected mock error. All is well!')),
730 )
731​
732 consoleMock.mockRestore()
733 })
734​
735 it('should be able to throw an error when throwOnError is a function that returns true', async () => {
736 const consoleMock = vi
737 .spyOn(console, 'error')
738 .mockImplementation(() => undefined)
739 let boundary = false
740 function Page() {
741 const { mutate, error } = useMutation<string, Error>({
742 mutationFn: () => {
743 const err = new Error('mock error')
744 err.stack = ''
745 return Promise.reject(err)
746 },
747 throwOnError: () => {
748 boundary = !boundary
749 return !boundary
750 },
751 })
752​
753 return (
754 <div>
755 <button onClick={() => mutate()}>mutate</button>
756 {error && error.message}
757 </div>
758 )
759 }
760​
761 const { getByText, queryByText } = renderWithClient(
762 queryClient,
763 <ErrorBoundary
764 fallbackRender={() => (
765 <div>
766 <span>error boundary</span>
767 </div>
768 )}
769 >
770 <Page />
771 </ErrorBoundary>,
772 )
773​
774 // first error goes to component
775 fireEvent.click(getByText('mutate'))
776 await waitFor(() => {
777 expect(queryByText('mock error')).not.toBeNull()
778 })
779​
780 // second error goes to boundary
781 fireEvent.click(getByText('mutate'))
782 await waitFor(() => {
783 expect(queryByText('error boundary')).not.toBeNull()
784 })
785 consoleMock.mockRestore()
786 })
787​
788 it('should pass meta to mutation', async () => {
789 const errorMock = vi.fn()
790 const successMock = vi.fn()
791​
792 const queryClientMutationMeta = createQueryClient({
793 mutationCache: new MutationCache({
794 onSuccess: (_, __, ___, mutation) => {
795 successMock(mutation.meta?.metaSuccessMessage)
796 },
797 onError: (_, __, ___, mutation) => {
798 errorMock(mutation.meta?.metaErrorMessage)
799 },
800 }),
801 })
802​
803 const metaSuccessMessage = 'mutation succeeded'
804 const metaErrorMessage = 'mutation failed'
805​
806 function Page() {
807 const { mutate: succeed, isSuccess } = useMutation({
808 mutationFn: async () => '',
809 meta: { metaSuccessMessage },
810 })
811 const { mutate: error, isError } = useMutation({
812 mutationFn: async () => {
813 throw new Error('')
814 },
815 meta: { metaErrorMessage },
816 })
817​
818 return (
819 <div>
820 <button onClick={() => succeed()}>succeed</button>
821 <button onClick={() => error()}>error</button>
822 {isSuccess && <div>successTest</div>}
823 {isError && <div>errorTest</div>}
824 </div>
825 )
826 }
827​
828 const { getByText, queryByText } = renderWithClient(
829 queryClientMutationMeta,
830 <Page />,
831 )
832​
833 fireEvent.click(getByText('succeed'))
834 fireEvent.click(getByText('error'))
835​
836 await waitFor(() => {
837 expect(queryByText('successTest')).not.toBeNull()
838 expect(queryByText('errorTest')).not.toBeNull()
839 })
840​
841 expect(successMock).toHaveBeenCalledTimes(1)
842 expect(successMock).toHaveBeenCalledWith(metaSuccessMessage)
843 expect(errorMock).toHaveBeenCalledTimes(1)
844 expect(errorMock).toHaveBeenCalledWith(metaErrorMessage)
845 })
846​
847 it('should call cache callbacks when unmounted', async () => {
848 const onSuccess = vi.fn()
849 const onSuccessMutate = vi.fn()
850 const onSettled = vi.fn()
851 const onSettledMutate = vi.fn()
852 const mutationKey = queryKey()
853 let count = 0
854​
855 function Page() {
856 const [show, setShow] = React.useState(true)
857 return (
858 <div>
859 <button onClick={() => setShow(false)}>hide</button>
860 {show && <Component />}
861 </div>
862 )
863 }
864​
865 function Component() {
866 const mutation = useMutation({
867 mutationFn: async (_text: string) => {
868 count++
869 await sleep(10)
870 return count
871 },
872 mutationKey,
873 gcTime: 0,
874 onSuccess,
875 onSettled,
876 })
877​
878 return (
879 <div>
880 <button
881 onClick={() =>
882 mutation.mutate('todo', {
883 onSuccess: onSuccessMutate,
884 onSettled: onSettledMutate,
885 })
886 }
887 >
888 mutate
889 </button>
890 <div>
891 data: {mutation.data ?? 'null'}, status: {mutation.status},
892 isPaused: {String(mutation.isPaused)}
893 </div>
894 </div>
895 )
896 }
897​
898 const rendered = renderWithClient(queryClient, <Page />)
899​
900 await rendered.findByText('data: null, status: idle, isPaused: false')
901​
902 fireEvent.click(rendered.getByRole('button', { name: /mutate/i }))
903 fireEvent.click(rendered.getByRole('button', { name: /hide/i }))
904​
905 await waitFor(() => {
906 expect(
907 queryClient.getMutationCache().findAll({ mutationKey }),
908 ).toHaveLength(0)
909 })
910​
911 expect(count).toBe(1)
912​
913 expect(onSuccess).toHaveBeenCalledTimes(1)
914 expect(onSettled).toHaveBeenCalledTimes(1)
915 expect(onSuccessMutate).toHaveBeenCalledTimes(0)
916 expect(onSettledMutate).toHaveBeenCalledTimes(0)
917 })
918​
919 it('should call mutate callbacks only for the last observer', async () => {
920 const onSuccess = vi.fn()
921 const onSuccessMutate = vi.fn()
922 const onSettled = vi.fn()
923 const onSettledMutate = vi.fn()
924 let count = 0
925​
926 function Page() {
927 const mutation = useMutation({
928 mutationFn: async (text: string) => {
929 count++
930 const result = `result-${text}`
931 await sleep(10)
932 return result
933 },
934 onSuccess,
935 onSettled,
936 })
937​
938 return (
939 <div>
940 <button
941 onClick={() =>
942 mutation.mutate('todo1', {
943 onSuccess: onSuccessMutate,
944 onSettled: onSettledMutate,
945 })
946 }
947 >
948 mutate1
949 </button>
950 <button
951 onClick={() =>
952 mutation.mutate('todo2', {
953 onSuccess: onSuccessMutate,
954 onSettled: onSettledMutate,
955 })
956 }
957 >
958 mutate2
959 </button>
960 <div>
961 data: {mutation.data ?? 'null'}, status: {mutation.status}
962 </div>
963 </div>
964 )
965 }
966​
967 const rendered = renderWithClient(queryClient, <Page />)
968​
969 await rendered.findByText('data: null, status: idle')
970​
971 fireEvent.click(rendered.getByRole('button', { name: /mutate1/i }))
972 fireEvent.click(rendered.getByRole('button', { name: /mutate2/i }))
973​
974 await rendered.findByText('data: result-todo2, status: success')
975​
976 expect(count).toBe(2)
977​
978 expect(onSuccess).toHaveBeenCalledTimes(2)
979 expect(onSuccess).toHaveBeenNthCalledWith(
980 1,
981 'result-todo1',
982 'todo1',
983 undefined,
984 )
985 expect(onSuccess).toHaveBeenNthCalledWith(
986 2,
987 'result-todo2',
988 'todo2',
989 undefined,
990 )
991 expect(onSettled).toHaveBeenCalledTimes(2)
992 expect(onSuccessMutate).toHaveBeenCalledTimes(1)
993 expect(onSuccessMutate).toHaveBeenCalledWith(
994 'result-todo2',
995 'todo2',
996 undefined,
997 )
998 expect(onSettledMutate).toHaveBeenCalledTimes(1)
999 expect(onSettledMutate).toHaveBeenCalledWith(
1000 'result-todo2',
1001 null,
1002 'todo2',
1003 undefined,
1005 })
1006​
1007 it('should go to error state if onSuccess callback errors', async () => {
1008 const error = new Error('error from onSuccess')
1009 const onError = vi.fn()
1010​
1011 function Page() {
1012 const mutation = useMutation({
1013 mutationFn: async (_text: string) => {
1014 await sleep(10)
1015 return 'result'
1016 },
1017 onSuccess: () => Promise.reject(error),
1018 onError,
1019 })
1020​
1021 return (
1022 <div>
1023 <button onClick={() => mutation.mutate('todo')}>mutate</button>
1024 <div>status: {mutation.status}</div>
1025 </div>
1028​
1029 const rendered = renderWithClient(queryClient, <Page />)
1030​
1031 await rendered.findByText('status: idle')
1032​
1033 rendered.getByRole('button', { name: /mutate/i }).click()
1034​
1035 await rendered.findByText('status: error')
1036​
1037 expect(onError).toHaveBeenCalledWith(error, 'todo', undefined)
1038 })
1039​
1040 it('should go to error state if onError callback errors', async () => {
1041 const error = new Error('error from onError')
1042 const mutateFnError = new Error('mutateFnError')
1043​
1044 function Page() {
1045 const mutation = useMutation({
1046 mutationFn: async (_text: string) => {
1047 await sleep(10)
1048 throw mutateFnError
1049 },
1050 onError: () => Promise.reject(error),
1051 })
1052​
1053 return (
1054 <div>
1055 <button onClick={() => mutation.mutate('todo')}>mutate</button>
1056 <div>
1057 error:{' '}
1058 {mutation.error instanceof Error ? mutation.error.message : 'null'},
1059 status: {mutation.status}
1060 </div>
1061 </div>
1064​
1065 const rendered = renderWithClient(queryClient, <Page />)
1066​
1067 await rendered.findByText('error: null, status: idle')
1068​
1069 rendered.getByRole('button', { name: /mutate/i }).click()
1070​
1071 await rendered.findByText('error: mutateFnError, status: error')
1072 })
1073​
1074 it('should go to error state if onSettled callback errors', async () => {
1075 const error = new Error('error from onSettled')
1076 const mutateFnError = new Error('mutateFnError')
1077 const onError = vi.fn()
1078​
1079 function Page() {
1080 const mutation = useMutation({
1081 mutationFn: async (_text: string) => {
1082 await sleep(10)
1083 throw mutateFnError
1084 },
1085 onSettled: () => Promise.reject(error),
1086 onError,
1087 })
1088​
1089 return (
1090 <div>
1091 <button onClick={() => mutation.mutate('todo')}>mutate</button>
1092 <div>
1093 error:{' '}
1094 {mutation.error instanceof Error ? mutation.error.message : 'null'},
1095 status: {mutation.status}
1096 </div>
1097 </div>
1100​
1101 const rendered = renderWithClient(queryClient, <Page />)
1102​
1103 await rendered.findByText('error: null, status: idle')
1104​
1105 rendered.getByRole('button', { name: /mutate/i }).click()
1106​
1107 await rendered.findByText('error: mutateFnError, status: error')
1108​
1109 expect(onError).toHaveBeenCalledWith(mutateFnError, 'todo', undefined)
1110 })
1111​
1112 it('should use provided custom queryClient', async () => {
1113 function Page() {
1114 const mutation = useMutation(
1116 mutationFn: async (text: string) => {
1117 return Promise.resolve(text)
1118 },
1119 },
1120 queryClient,
1122​
1123 return (
1124 <div>
1125 <button onClick={() => mutation.mutate('custom client')}>
1126 mutate
1127 </button>
1128 <div>
1129 data: {mutation.data ?? 'null'}, status: {mutation.status}
1130 </div>
1131 </div>
1134​
1135 const rendered = render(<Page></Page>)
1136​
1137 await rendered.findByText('data: null, status: idle')
1138​
1139 fireEvent.click(rendered.getByRole('button', { name: /mutate/i }))
1140​
1141 await rendered.findByText('data: custom client, status: success')
1142 })