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

useMutation.test.tsx

1,100 lines28.0 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 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 },
1001 onSuccess: () => Promise.reject(error),
1002 onError,
1003 },
1005​
1006 return (
1007 <div>
1008 <button onClick={() => mutation.mutate('todo')}>mutate</button>
1009 <div>status: {mutation.status}</div>
1010 </div>
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 },
1036 onError: () => Promise.reject(error),
1037 },
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>
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 },
1073 onSettled: () => Promise.reject(error),
1074 onError,
1075 },
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>
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 })