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