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