Open History to see the last commit
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,
1004 )
1005 expect(onSuccess).toHaveBeenNthCalledWith(
1006 2,
1007 'result-todo2',
1008 'todo2',
1009 undefined,
1010 )
1011 expect(onSettled).toHaveBeenCalledTimes(2)
1012 expect(onSuccessMutate).toHaveBeenCalledTimes(1)
1013 expect(onSuccessMutate).toHaveBeenCalledWith(
1014 'result-todo2',
1015 'todo2',
1016 undefined,
1017 )
1018 expect(onSettledMutate).toHaveBeenCalledTimes(1)
1019 expect(onSettledMutate).toHaveBeenCalledWith(
1020 'result-todo2',
1021 null,
1022 'todo2',
1023 undefined,
1024 )
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>
1046 )
1047 }
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>
1082 )
1083 }
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'),
1093 )
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>
1120 )
1121 }
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'),
1131 )
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(
1139 {
1140 mutationFn: async (text: string) => {
1141 return Promise.resolve(text)
1142 },
1143 },
1144 queryClient,
1145 )
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>
1156 )
1157 }
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'),
1167 )
1168 })
1169})