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

useMutation.test.tsx

1,213 lines31.4 KB

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