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

useMutation.test.tsx

1,096 lines27.9 KB

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