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

useMutation.test.tsx

1,169 lines30.9 KB

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