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

useMutation.test.tsx

1,240 lines35.8 KB

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