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

useMutation.test.tsx

1,145 lines30.0 KB

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 { vi } from 'vitest'
7import { MutationCache, QueryCache, useMutation } from '..'
8import {
9 createQueryClient,
10 mockOnlineManagerIsOnline,
11 queryKey,
12 renderWithClient,
13 setActTimeout,
14 sleep,
15} from './utils'
16import type { UseMutationResult } from '../types'
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({ mutationFn: () => 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 mutationFn: () => {
61 const err = new Error('Expected mock error. All is well!')
62 err.stack = ''
63 return Promise.reject(err)
64 },
65 })
66​
67 return (
68 <div>
69 {error && <h1>{error.message}</h1>}
70 <button onClick={() => reset()}>reset</button>
71 <button onClick={() => mutate()}>mutate</button>
72 </div>
73 )
74 }
75​
76 const { getByRole, queryByRole } = renderWithClient(queryClient, <Page />)
77​
78 await waitFor(() => {
79 expect(queryByRole('heading')).toBeNull()
80 })
81​
82 fireEvent.click(getByRole('button', { name: /mutate/i }))
83​
84 await waitFor(() => {
85 expect(getByRole('heading').textContent).toBe(
86 'Expected mock error. All is well!',
87 )
88 })
89​
90 fireEvent.click(getByRole('button', { name: /reset/i }))
91​
92 await waitFor(() => {
93 expect(queryByRole('heading')).toBeNull()
94 })
95 })
96​
97 it('should be able to call `onSuccess` and `onSettled` after each successful mutate', async () => {
98 let count = 0
99 const onSuccessMock = vi.fn()
100 const onSettledMock = vi.fn()
101​
102 function Page() {
103 const { mutate } = useMutation({
104 mutationFn: (vars: { count: number }) => Promise.resolve(vars.count),
105​
106 onSuccess: (data) => {
107 onSuccessMock(data)
108 },
109 onSettled: (data) => {
110 onSettledMock(data)
111 },
112 })
113​
114 return (
115 <div>
116 <h1>{count}</h1>
117 <button onClick={() => mutate({ count: ++count })}>mutate</button>
118 </div>
119 )
120 }
121​
122 const { getByRole } = renderWithClient(queryClient, <Page />)
123​
124 expect(getByRole('heading').textContent).toBe('0')
125​
126 fireEvent.click(getByRole('button', { name: /mutate/i }))
127 fireEvent.click(getByRole('button', { name: /mutate/i }))
128 fireEvent.click(getByRole('button', { name: /mutate/i }))
129​
130 await waitFor(() => {
131 expect(getByRole('heading').textContent).toBe('3')
132 })
133​
134 await waitFor(() => {
135 expect(onSuccessMock).toHaveBeenCalledTimes(3)
136 })
137​
138 expect(onSuccessMock).toHaveBeenCalledWith(1)
139 expect(onSuccessMock).toHaveBeenCalledWith(2)
140 expect(onSuccessMock).toHaveBeenCalledWith(3)
141​
142 await waitFor(() => {
143 expect(onSettledMock).toHaveBeenCalledTimes(3)
144 })
145​
146 expect(onSettledMock).toHaveBeenCalledWith(1)
147 expect(onSettledMock).toHaveBeenCalledWith(2)
148 expect(onSettledMock).toHaveBeenCalledWith(3)
149 })
150​
151 it('should set correct values for `failureReason` and `failureCount` on multiple mutate calls', async () => {
152 let count = 0
153 type Value = { count: number }
154​
155 const mutateFn = vi.fn<[value: Value], Promise<Value>>()
156​
157 mutateFn.mockImplementationOnce(() => {
158 return Promise.reject(new Error('Error test Jonas'))
159 })
160​
161 mutateFn.mockImplementation(async (value) => {
162 await sleep(10)
163 return Promise.resolve(value)
164 })
165​
166 function Page() {
167 const { mutate, failureCount, failureReason, data, status } = useMutation(
168 { mutationFn: mutateFn },
169 )
170​
171 return (
172 <div>
173 <h1>Data {data?.count}</h1>
174 <h2>Status {status}</h2>
175 <h2>Failed {failureCount} times</h2>
176 <h2>Failed because {failureReason?.message ?? 'null'}</h2>
177 <button onClick={() => mutate({ count: ++count })}>mutate</button>
178 </div>
179 )
180 }
181​
182 const rendered = renderWithClient(queryClient, <Page />)
183​
184 await waitFor(() => rendered.getByText('Data'))
185​
186 fireEvent.click(rendered.getByRole('button', { name: /mutate/i }))
187 await waitFor(() => rendered.getByText('Data'))
188 await waitFor(() => rendered.getByText('Status error'))
189 await waitFor(() => rendered.getByText('Failed 1 times'))
190 await waitFor(() => rendered.getByText('Failed because Error test Jonas'))
191​
192 fireEvent.click(rendered.getByRole('button', { name: /mutate/i }))
193 await waitFor(() => rendered.getByText('Status pending'))
194 await waitFor(() => rendered.getByText('Status success'))
195 await waitFor(() => rendered.getByText('Data 2'))
196 await waitFor(() => rendered.getByText('Failed 0 times'))
197 await waitFor(() => rendered.getByText('Failed because null'))
198 })
199​
200 it('should be able to call `onError` and `onSettled` after each failed mutate', async () => {
201 const onErrorMock = vi.fn()
202 const onSettledMock = vi.fn()
203 let count = 0
204​
205 function Page() {
206 const { mutate } = useMutation({
207 mutationFn: (vars: { count: number }) => {
208 const error = new Error(
209 `Expected mock error. All is well! ${vars.count}`,
210 )
211 error.stack = ''
212 return Promise.reject(error)
213 },
214 onError: (error: Error) => {
215 onErrorMock(error.message)
216 },
217 onSettled: (_data, error) => {
218 onSettledMock(error?.message)
219 },
220 })
221​
222 return (
223 <div>
224 <h1>{count}</h1>
225 <button onClick={() => mutate({ count: ++count })}>mutate</button>
226 </div>
227 )
228 }
229​
230 const { getByRole } = renderWithClient(queryClient, <Page />)
231​
232 expect(getByRole('heading').textContent).toBe('0')
233​
234 fireEvent.click(getByRole('button', { name: /mutate/i }))
235 fireEvent.click(getByRole('button', { name: /mutate/i }))
236 fireEvent.click(getByRole('button', { name: /mutate/i }))
237​
238 await waitFor(() => {
239 expect(getByRole('heading').textContent).toBe('3')
240 })
241​
242 await waitFor(() => {
243 expect(onErrorMock).toHaveBeenCalledTimes(3)
244 })
245 expect(onErrorMock).toHaveBeenCalledWith(
246 'Expected mock error. All is well! 1',
247 )
248 expect(onErrorMock).toHaveBeenCalledWith(
249 'Expected mock error. All is well! 2',
250 )
251 expect(onErrorMock).toHaveBeenCalledWith(
252 'Expected mock error. All is well! 3',
253 )
254​
255 await waitFor(() => {
256 expect(onSettledMock).toHaveBeenCalledTimes(3)
257 })
258 expect(onSettledMock).toHaveBeenCalledWith(
259 'Expected mock error. All is well! 1',
260 )
261 expect(onSettledMock).toHaveBeenCalledWith(
262 'Expected mock error. All is well! 2',
263 )
264 expect(onSettledMock).toHaveBeenCalledWith(
265 'Expected mock error. All is well! 3',
266 )
267 })
268​
269 it('should be able to override the useMutation success callbacks', async () => {
270 const callbacks: Array<string> = []
271​
272 function Page() {
273 const { mutateAsync } = useMutation({
274 mutationFn: async (text: string) => text,
275 onSuccess: async () => {
276 callbacks.push('useMutation.onSuccess')
277 },
278 onSettled: async () => {
279 callbacks.push('useMutation.onSettled')
280 },
281 })
282​
283 React.useEffect(() => {
284 setActTimeout(async () => {
285 try {
286 const result = await mutateAsync('todo', {
287 onSuccess: async () => {
288 callbacks.push('mutateAsync.onSuccess')
289 },
290 onSettled: async () => {
291 callbacks.push('mutateAsync.onSettled')
292 },
293 })
294 callbacks.push(`mutateAsync.result:${result}`)
295 } catch {}
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.onSuccess',
308 'useMutation.onSettled',
309 'mutateAsync.onSuccess',
310 'mutateAsync.onSettled',
311 'mutateAsync.result:todo',
312 ])
313 })
314​
315 it('should be able to override the error callbacks when using mutateAsync', async () => {
316 const callbacks: Array<string> = []
317​
318 function Page() {
319 const { mutateAsync } = useMutation({
320 mutationFn: async (_text: string) => Promise.reject(new Error('oops')),
321 onError: async () => {
322 callbacks.push('useMutation.onError')
323 },
324 onSettled: async () => {
325 callbacks.push('useMutation.onSettled')
326 },
327 })
328​
329 React.useEffect(() => {
330 setActTimeout(async () => {
331 try {
332 await mutateAsync('todo', {
333 onError: async () => {
334 callbacks.push('mutateAsync.onError')
335 },
336 onSettled: async () => {
337 callbacks.push('mutateAsync.onSettled')
338 },
339 })
340 } catch (error) {
341 callbacks.push(`mutateAsync.error:${(error as Error).message}`)
342 }
343 }, 10)
344 }, [mutateAsync])
345​
346 return null
347 }
348​
349 renderWithClient(queryClient, <Page />)
350​
351 await sleep(100)
352​
353 expect(callbacks).toEqual([
354 'useMutation.onError',
355 'useMutation.onSettled',
356 'mutateAsync.onError',
357 'mutateAsync.onSettled',
358 'mutateAsync.error:oops',
359 ])
360 })
361​
362 it('should be able to use mutation defaults', async () => {
363 const key = queryKey()
364​
365 queryClient.setMutationDefaults(key, {
366 mutationFn: async (text: string) => {
367 await sleep(10)
368 return text
369 },
370 })
371​
372 const states: Array<UseMutationResult<any, any, any, any>> = []
373​
374 function Page() {
375 const state = useMutation<string, unknown, string>({ mutationKey: key })
376​
377 states.push(state)
378​
379 const { mutate } = state
380​
381 React.useEffect(() => {
382 setActTimeout(() => {
383 mutate('todo')
384 }, 10)
385 }, [mutate])
386​
387 return null
388 }
389​
390 renderWithClient(queryClient, <Page />)
391​
392 await sleep(100)
393​
394 expect(states.length).toBe(3)
395 expect(states[0]).toMatchObject({ data: undefined, isPending: false })
396 expect(states[1]).toMatchObject({ data: undefined, isPending: true })
397 expect(states[2]).toMatchObject({ data: 'todo', isPending: false })
398 })
399​
400 it('should be able to retry a failed mutation', async () => {
401 let count = 0
402​
403 function Page() {
404 const { mutate } = useMutation({
405 mutationFn: (_text: string) => {
406 count++
407 return Promise.reject(new Error('oops'))
408 },
409 retry: 1,
410 retryDelay: 5,
411 })
412​
413 React.useEffect(() => {
414 setActTimeout(() => {
415 mutate('todo')
416 }, 10)
417 }, [mutate])
418​
419 return null
420 }
421​
422 renderWithClient(queryClient, <Page />)
423​
424 await sleep(100)
425​
426 expect(count).toBe(2)
427 })
428​
429 it('should not retry mutations while offline', async () => {
430 const onlineMock = mockOnlineManagerIsOnline(false)
431​
432 let count = 0
433​
434 function Page() {
435 const mutation = useMutation({
436 mutationFn: (_text: string) => {
437 count++
438 return Promise.reject(new Error('oops'))
439 },
440 retry: 1,
441 retryDelay: 5,
442 })
443​
444 return (
445 <div>
446 <button onClick={() => mutation.mutate('todo')}>mutate</button>
447 <div>
448 error:{' '}
449 {mutation.error instanceof Error ? mutation.error.message : 'null'},
450 status: {mutation.status}, isPaused: {String(mutation.isPaused)}
451 </div>
452 </div>
453 )
454 }
455​
456 const rendered = renderWithClient(queryClient, <Page />)
457​
458 window.dispatchEvent(new Event('offline'))
459​
460 await waitFor(() => {
461 expect(
462 rendered.getByText('error: null, status: idle, isPaused: false'),
463 ).toBeInTheDocument()
464 })
465​
466 fireEvent.click(rendered.getByRole('button', { name: /mutate/i }))
467​
468 await waitFor(() => {
469 expect(
470 rendered.getByText('error: null, status: pending, isPaused: true'),
471 ).toBeInTheDocument()
472 })
473​
474 expect(count).toBe(0)
475​
476 onlineMock.mockRestore()
477 window.dispatchEvent(new Event('online'))
478​
479 await sleep(100)
480​
481 await waitFor(() => {
482 expect(
483 rendered.getByText('error: oops, status: error, isPaused: false'),
484 ).toBeInTheDocument()
485 })
486​
487 expect(count).toBe(2)
488 })
489​
490 it('should call onMutate even if paused', async () => {
491 const onlineMock = mockOnlineManagerIsOnline(false)
492 const onMutate = vi.fn()
493 let count = 0
494​
495 function Page() {
496 const mutation = useMutation({
497 mutationFn: async (_text: string) => {
498 count++
499 await sleep(10)
500 return count
501 },
502 onMutate,
503 })
504​
505 return (
506 <div>
507 <button onClick={() => mutation.mutate('todo')}>mutate</button>
508 <div>
509 data: {mutation.data ?? 'null'}, status: {mutation.status},
510 isPaused: {String(mutation.isPaused)}
511 </div>
512 </div>
513 )
514 }
515​
516 const rendered = renderWithClient(queryClient, <Page />)
517​
518 await rendered.findByText('data: null, status: idle, isPaused: false')
519​
520 window.dispatchEvent(new Event('offline'))
521​
522 fireEvent.click(rendered.getByRole('button', { name: /mutate/i }))
523​
524 await rendered.findByText('data: null, status: pending, isPaused: true')
525​
526 expect(onMutate).toHaveBeenCalledTimes(1)
527 expect(onMutate).toHaveBeenCalledWith('todo')
528​
529 onlineMock.mockRestore()
530 window.dispatchEvent(new Event('online'))
531​
532 await rendered.findByText('data: 1, status: success, isPaused: false')
533​
534 expect(onMutate).toHaveBeenCalledTimes(1)
535 expect(count).toBe(1)
536 })
537​
538 it('should optimistically go to paused state if offline', async () => {
539 const onlineMock = mockOnlineManagerIsOnline(false)
540 let count = 0
541 const states: Array<string> = []
542​
543 function Page() {
544 const mutation = useMutation({
545 mutationFn: async (_text: string) => {
546 count++
547 await sleep(10)
548 return count
549 },
550 })
551​
552 states.push(`${mutation.status}, ${mutation.isPaused}`)
553​
554 return (
555 <div>
556 <button onClick={() => mutation.mutate('todo')}>mutate</button>
557 <div>
558 data: {mutation.data ?? 'null'}, status: {mutation.status},
559 isPaused: {String(mutation.isPaused)}
560 </div>
561 </div>
562 )
563 }
564​
565 const rendered = renderWithClient(queryClient, <Page />)
566​
567 await rendered.findByText('data: null, status: idle, isPaused: false')
568​
569 window.dispatchEvent(new Event('offline'))
570​
571 fireEvent.click(rendered.getByRole('button', { name: /mutate/i }))
572​
573 await rendered.findByText('data: null, status: pending, isPaused: true')
574​
575 // no intermediate 'pending, false' state is expected because we don't start mutating!
576 expect(states[0]).toBe('idle, false')
577 expect(states[1]).toBe('pending, true')
578​
579 onlineMock.mockRestore()
580 window.dispatchEvent(new Event('online'))
581​
582 await rendered.findByText('data: 1, status: success, isPaused: false')
583 })
584​
585 it('should be able to retry a mutation when online', async () => {
586 const onlineMock = mockOnlineManagerIsOnline(false)
587​
588 let count = 0
589 const states: Array<UseMutationResult<any, any, any, any>> = []
590​
591 function Page() {
592 const state = useMutation({
593 mutationFn: async (_text: string) => {
594 await sleep(1)
595 count++
596 return count > 1
597 ? Promise.resolve('data')
598 : Promise.reject(new Error('oops'))
599 },
600 retry: 1,
601 retryDelay: 5,
602 networkMode: 'offlineFirst',
603 })
604​
605 states.push(state)
606​
607 const { mutate } = state
608​
609 React.useEffect(() => {
610 setActTimeout(() => {
611 window.dispatchEvent(new Event('offline'))
612 mutate('todo')
613 }, 10)
614 }, [mutate])
615​
616 return null
617 }
618​
619 renderWithClient(queryClient, <Page />)
620​
621 await sleep(50)
622​
623 expect(states.length).toBe(4)
624 expect(states[0]).toMatchObject({
625 isPending: false,
626 isPaused: false,
627 failureCount: 0,
628 failureReason: null,
629 })
630 expect(states[1]).toMatchObject({
631 isPending: true,
632 isPaused: false,
633 failureCount: 0,
634 failureReason: null,
635 })
636 expect(states[2]).toMatchObject({
637 isPending: true,
638 isPaused: false,
639 failureCount: 1,
640 failureReason: new Error('oops'),
641 })
642 expect(states[3]).toMatchObject({
643 isPending: true,
644 isPaused: true,
645 failureCount: 1,
646 failureReason: new Error('oops'),
647 })
648​
649 onlineMock.mockRestore()
650 window.dispatchEvent(new Event('online'))
651​
652 await sleep(50)
653​
654 expect(states.length).toBe(6)
655 expect(states[4]).toMatchObject({
656 isPending: true,
657 isPaused: false,
658 failureCount: 1,
659 failureReason: new Error('oops'),
660 })
661 expect(states[5]).toMatchObject({
662 isPending: false,
663 isPaused: false,
664 failureCount: 0,
665 failureReason: null,
666 data: 'data',
667 })
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 throwOnError is set to true', async () => {
691 const consoleMock = vi
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 throwOnError: 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 throwOnError is a function that returns true', async () => {
738 const consoleMock = vi
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 throwOnError: () => {
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 = vi.fn()
792 const successMock = vi.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 = vi.fn()
851 const onSuccessMutate = vi.fn()
852 const onSettled = vi.fn()
853 const onSettledMutate = vi.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 = vi.fn()
923 const onSuccessMutate = vi.fn()
924 const onSettled = vi.fn()
925 const onSettledMutate = vi.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,
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 = vi.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>
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>
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 = vi.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>
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(
1118 mutationFn: async (text: string) => {
1119 return Promise.resolve(text)
1120 },
1121 },
1122 queryClient,
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>
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 })