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

createMutation.svelte.test.ts

706 lines21.3 KB

1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2import { flushSync } from 'svelte'
3import { fireEvent, render } from '@testing-library/svelte'
4import { QueryClient, noop } from '@tanstack/query-core'
5import { queryKey, sleep } from '@tanstack/query-test-utils'
6import { createMutation } from '../../src/index.js'
7import { withEffectRoot } from '../utils.svelte.js'
8import Reset from './Reset.svelte'
9import Success from './Success.svelte'
10import Failure from './Failure.svelte'
11import OptimisticUpdate from './OptimisticUpdate.svelte'
12import SuccessContext from './SuccessContext.svelte'
13import InvalidateFromContext from './InvalidateFromContext.svelte'
14import PerCallSuccess from './PerCallSuccess.svelte'
15import MutationFnContext from './MutationFnContext.svelte'
16import ParallelMutateAsync from './ParallelMutateAsync.svelte'
17import ConcurrentMutate from './ConcurrentMutate.svelte'
18​
19describe('createMutation', () => {
20 let queryClient: QueryClient
21​
22 beforeEach(() => {
23 vi.useFakeTimers()
24 queryClient = new QueryClient()
25 })
26​
27 afterEach(() => {
28 queryClient.clear()
29 vi.useRealTimers()
30 })
31​
32 it('should be able to reset `error`', async () => {
33 const rendered = render(Reset, {
34 props: { queryClient },
35 })
36​
37 expect(rendered.queryByText('Error: undefined')).toBeInTheDocument()
38​
39 fireEvent.click(rendered.getByRole('button', { name: /Mutate/i }))
40 await vi.advanceTimersByTimeAsync(11)
41 expect(rendered.getByText('Error: Expected mock error')).toBeInTheDocument()
42​
43 fireEvent.click(rendered.getByRole('button', { name: /Reset/i }))
44 await vi.advanceTimersByTimeAsync(11)
45 expect(rendered.getByText('Error: undefined')).toBeInTheDocument()
46 })
47​
48 it(
49 'should call mutate callbacks when createMutation has no callbacks',
50 withEffectRoot(async () => {
51 const callbacks: Array<string> = []
52​
53 const mutation = createMutation(
54 () => ({
55 mutationFn: (text: string) => sleep(10).then(() => text),
56 }),
57 () => queryClient,
58 )
59​
60 mutation.mutate('todo', {
61 onSuccess: () => callbacks.push('mutate.onSuccess'),
62 onSettled: () => callbacks.push('mutate.onSettled'),
63 })
64 await vi.advanceTimersByTimeAsync(10)
65​
66 expect(callbacks).toEqual(['mutate.onSuccess', 'mutate.onSettled'])
67 }),
68 )
69​
70 it(
71 'should call mutate error callbacks when createMutation has no callbacks',
72 withEffectRoot(async () => {
73 const callbacks: Array<string> = []
74​
75 const mutation = createMutation(
76 () => ({
77 mutationFn: (_text: string) =>
78 sleep(10).then(() => Promise.reject(new Error('oops'))),
79 }),
80 () => queryClient,
81 )
82​
83 mutation.mutate('todo', {
84 onError: () => callbacks.push('mutate.onError'),
85 onSettled: () => callbacks.push('mutate.onSettled'),
86 })
87 await vi.advanceTimersByTimeAsync(10)
88​
89 expect(callbacks).toEqual(['mutate.onError', 'mutate.onSettled'])
90 }),
91 )
92​
93 it(
94 'should call only mutate onSuccess when createMutation has no callbacks',
95 withEffectRoot(async () => {
96 const callbacks: Array<string> = []
97​
98 const mutation = createMutation(
99 () => ({
100 mutationFn: (text: string) => sleep(10).then(() => text),
101 }),
102 () => queryClient,
103 )
104​
105 mutation.mutate('todo', {
106 onSuccess: () => callbacks.push('mutate.onSuccess'),
107 })
108 await vi.advanceTimersByTimeAsync(10)
109​
110 expect(callbacks).toEqual(['mutate.onSuccess'])
111 }),
112 )
113​
114 it(
115 'should call only mutate onError when createMutation has no callbacks',
116 withEffectRoot(async () => {
117 const callbacks: Array<string> = []
118​
119 const mutation = createMutation(
120 () => ({
121 mutationFn: (_text: string) =>
122 sleep(10).then(() => Promise.reject(new Error('oops'))),
123 }),
124 () => queryClient,
125 )
126​
127 mutation.mutate('todo', {
128 onError: () => callbacks.push('mutate.onError'),
129 })
130 await vi.advanceTimersByTimeAsync(10)
131​
132 expect(callbacks).toEqual(['mutate.onError'])
133 }),
134 )
135​
136 it(
137 'should call only mutate onSettled when createMutation has no callbacks',
138 withEffectRoot(async () => {
139 const callbacks: Array<string> = []
140​
141 const mutation = createMutation(
142 () => ({
143 mutationFn: (text: string) => sleep(10).then(() => text),
144 }),
145 () => queryClient,
146 )
147​
148 mutation.mutate('todo', {
149 onSettled: () => callbacks.push('mutate.onSettled'),
150 })
151 await vi.advanceTimersByTimeAsync(10)
152​
153 expect(callbacks).toEqual(['mutate.onSettled'])
154 }),
155 )
156​
157 it(
158 'should call mutateAsync callbacks when createMutation has no callbacks',
159 withEffectRoot(async () => {
160 const callbacks: Array<string> = []
161​
162 const mutation = createMutation(
163 () => ({
164 mutationFn: (text: string) => sleep(10).then(() => text),
165 }),
166 () => queryClient,
167 )
168​
169 mutation.mutateAsync('todo', {
170 onSuccess: () => callbacks.push('mutateAsync.onSuccess'),
171 onSettled: () => callbacks.push('mutateAsync.onSettled'),
172 })
173 await vi.advanceTimersByTimeAsync(10)
174​
175 expect(callbacks).toEqual([
176 'mutateAsync.onSuccess',
177 'mutateAsync.onSettled',
178 ])
179 }),
180 )
181​
182 it(
183 'should call mutateAsync error callbacks when createMutation has no callbacks',
184 withEffectRoot(async () => {
185 const callbacks: Array<string> = []
186​
187 const mutation = createMutation(
188 () => ({
189 mutationFn: (_text: string) =>
190 sleep(10).then(() => Promise.reject(new Error('oops'))),
191 }),
192 () => queryClient,
193 )
194​
195 mutation
196 .mutateAsync('todo', {
197 onError: () => callbacks.push('mutateAsync.onError'),
198 onSettled: () => callbacks.push('mutateAsync.onSettled'),
199 })
200 .catch(noop)
201 await vi.advanceTimersByTimeAsync(10)
202​
203 expect(callbacks).toEqual([
204 'mutateAsync.onError',
205 'mutateAsync.onSettled',
206 ])
207 }),
208 )
209​
210 it(
211 'should call only mutateAsync onSuccess when createMutation has no callbacks',
212 withEffectRoot(async () => {
213 const callbacks: Array<string> = []
214​
215 const mutation = createMutation(
216 () => ({
217 mutationFn: (text: string) => sleep(10).then(() => text),
218 }),
219 () => queryClient,
220 )
221​
222 mutation.mutateAsync('todo', {
223 onSuccess: () => callbacks.push('mutateAsync.onSuccess'),
224 })
225 await vi.advanceTimersByTimeAsync(10)
226​
227 expect(callbacks).toEqual(['mutateAsync.onSuccess'])
228 }),
229 )
230​
231 it(
232 'should call only mutateAsync onError when createMutation has no callbacks',
233 withEffectRoot(async () => {
234 const callbacks: Array<string> = []
235​
236 const mutation = createMutation(
237 () => ({
238 mutationFn: (_text: string) =>
239 sleep(10).then(() => Promise.reject(new Error('oops'))),
240 }),
241 () => queryClient,
242 )
243​
244 mutation
245 .mutateAsync('todo', {
246 onError: () => callbacks.push('mutateAsync.onError'),
247 })
248 .catch(noop)
249 await vi.advanceTimersByTimeAsync(10)
250​
251 expect(callbacks).toEqual(['mutateAsync.onError'])
252 }),
253 )
254​
255 it(
256 'should call only mutateAsync onSettled when createMutation has no callbacks',
257 withEffectRoot(async () => {
258 const callbacks: Array<string> = []
259​
260 const mutation = createMutation(
261 () => ({
262 mutationFn: (text: string) => sleep(10).then(() => text),
263 }),
264 () => queryClient,
265 )
266​
267 mutation.mutateAsync('todo', {
268 onSettled: () => callbacks.push('mutateAsync.onSettled'),
269 })
270 await vi.advanceTimersByTimeAsync(10)
271​
272 expect(callbacks).toEqual(['mutateAsync.onSettled'])
273 }),
274 )
275​
276 it('should be able to call `onSuccess` and `onSettled` after each successful mutate', async () => {
277 const onSuccessMock = vi.fn()
278 const onSettledMock = vi.fn()
279​
280 const rendered = render(Success, {
281 props: {
282 queryClient,
283 onSuccessMock,
284 onSettledMock,
285 },
286 })
287​
288 expect(rendered.queryByText('Count: 0')).toBeInTheDocument()
289​
290 fireEvent.click(rendered.getByRole('button', { name: /Mutate/i }))
291 fireEvent.click(rendered.getByRole('button', { name: /Mutate/i }))
292 fireEvent.click(rendered.getByRole('button', { name: /Mutate/i }))
293 await vi.advanceTimersByTimeAsync(11)
294 expect(rendered.queryByText('Count: 3')).toBeInTheDocument()
295​
296 expect(onSuccessMock).toHaveBeenCalledTimes(3)
297 expect(onSuccessMock).toHaveBeenNthCalledWith(1, 1)
298 expect(onSuccessMock).toHaveBeenNthCalledWith(2, 2)
299 expect(onSuccessMock).toHaveBeenNthCalledWith(3, 3)
300​
301 expect(onSettledMock).toHaveBeenCalledTimes(3)
302 expect(onSettledMock).toHaveBeenNthCalledWith(1, 1)
303 expect(onSettledMock).toHaveBeenNthCalledWith(2, 2)
304 expect(onSettledMock).toHaveBeenNthCalledWith(3, 3)
305 })
306​
307 it('should set correct values for `failureReason` and `failureCount` on multiple mutate calls', async () => {
308 type Value = { count: number }
309​
310 const mutationFn = vi.fn<(value: Value) => Promise<Value>>()
311​
312 mutationFn.mockImplementationOnce(() =>
313 sleep(20).then(() => Promise.reject(`Expected mock error`)),
314 )
315​
316 mutationFn.mockImplementation((value) => sleep(10).then(() => value))
317​
318 const rendered = render(Failure, {
319 props: {
320 queryClient,
321 mutationFn,
322 },
323 })
324​
325 expect(rendered.queryByText('Data: undefined')).toBeInTheDocument()
326​
327 fireEvent.click(rendered.getByRole('button', { name: /Mutate/i }))
328 expect(rendered.getByText('Data: undefined')).toBeInTheDocument()
329 await vi.advanceTimersByTimeAsync(21)
330 expect(rendered.getByText('Status: error')).toBeInTheDocument()
331 expect(rendered.getByText('Failure Count: 1')).toBeInTheDocument()
332 expect(
333 rendered.getByText('Failure Reason: Expected mock error'),
334 ).toBeInTheDocument()
335​
336 fireEvent.click(rendered.getByRole('button', { name: /Mutate/i }))
337 await vi.advanceTimersByTimeAsync(0)
338 expect(rendered.getByText('Status: pending')).toBeInTheDocument()
339 await vi.advanceTimersByTimeAsync(11)
340 expect(rendered.getByText('Status: success')).toBeInTheDocument()
341 expect(rendered.getByText('Data: 2')).toBeInTheDocument()
342 expect(rendered.getByText('Failure Count: 0')).toBeInTheDocument()
343 expect(rendered.getByText('Failure Reason: undefined')).toBeInTheDocument()
344 })
345​
346 it(
347 'should be able to call `onSuccess` callback after successful mutateAsync',
348 withEffectRoot(async () => {
349 const callbacks: Array<string> = []
350​
351 const mutation = createMutation(
352 () => ({
353 mutationFn: (text: string) => sleep(10).then(() => text),
354 onSuccess: () => callbacks.push('useMutation.onSuccess'),
355 }),
356 () => queryClient,
357 )
358​
359 mutation.mutateAsync('todo', {
360 onSuccess: () => callbacks.push('mutateAsync.onSuccess'),
361 })
362 await vi.advanceTimersByTimeAsync(10)
363​
364 expect(callbacks).toEqual([
365 'useMutation.onSuccess',
366 'mutateAsync.onSuccess',
367 ])
368 }),
369 )
370​
371 it(
372 'should be able to call `onError` callback after failed mutateAsync',
373 withEffectRoot(async () => {
374 const callbacks: Array<string> = []
375​
376 const mutation = createMutation(
377 () => ({
378 mutationFn: (_text: string) =>
379 sleep(10).then(() => Promise.reject(new Error('oops'))),
380 onError: () => callbacks.push('useMutation.onError'),
381 }),
382 () => queryClient,
383 )
384​
385 mutation
386 .mutateAsync('todo', {
387 onError: () => callbacks.push('mutateAsync.onError'),
388 })
389 .catch(noop)
390 await vi.advanceTimersByTimeAsync(10)
391​
392 expect(callbacks).toEqual(['useMutation.onError', 'mutateAsync.onError'])
393 }),
394 )
395​
396 it(
397 'should be able to call `onSettled` callback after mutateAsync',
398 withEffectRoot(async () => {
399 const callbacks: Array<string> = []
400​
401 const mutation = createMutation(
402 () => ({
403 mutationFn: (text: string) => sleep(10).then(() => text),
404 onSettled: () => callbacks.push('useMutation.onSettled'),
405 }),
406 () => queryClient,
407 )
408​
409 mutation.mutateAsync('todo', {
410 onSettled: () => callbacks.push('mutateAsync.onSettled'),
411 })
412 await vi.advanceTimersByTimeAsync(10)
413​
414 expect(callbacks).toEqual([
415 'useMutation.onSettled',
416 'mutateAsync.onSettled',
417 ])
418 }),
419 )
420​
421 it(
422 'should be able to override the useMutation success callbacks',
423 withEffectRoot(async () => {
424 const callbacks: Array<string> = []
425​
426 const mutation = createMutation(
427 () => ({
428 mutationFn: (text: string) => sleep(10).then(() => text),
429 onSuccess: () =>
430 sleep(10).then(() => callbacks.push('useMutation.onSuccess')),
431 onSettled: () =>
432 sleep(10).then(() => callbacks.push('useMutation.onSettled')),
433 }),
434 () => queryClient,
435 )
436​
437 mutation
438 .mutateAsync('todo', {
439 onSuccess: () => callbacks.push('mutateAsync.onSuccess'),
440 onSettled: () => callbacks.push('mutateAsync.onSettled'),
441 })
442 .then((result) => callbacks.push(`mutateAsync.result:${result}`))
443 await vi.advanceTimersByTimeAsync(30)
444​
445 expect(callbacks).toEqual([
446 'useMutation.onSuccess',
447 'useMutation.onSettled',
448 'mutateAsync.onSuccess',
449 'mutateAsync.onSettled',
450 'mutateAsync.result:todo',
451 ])
452 }),
453 )
454​
455 it(
456 'should be able to override the error callbacks when using mutateAsync',
457 withEffectRoot(async () => {
458 const callbacks: Array<string> = []
459​
460 const mutation = createMutation(
461 () => ({
462 mutationFn: (_text: string) =>
463 sleep(10).then(() => Promise.reject(new Error('oops'))),
464 onError: () =>
465 sleep(10).then(() => callbacks.push('useMutation.onError')),
466 onSettled: () =>
467 sleep(10).then(() => callbacks.push('useMutation.onSettled')),
468 }),
469 () => queryClient,
470 )
471​
472 mutation
473 .mutateAsync('todo', {
474 onError: () => callbacks.push('mutateAsync.onError'),
475 onSettled: () => callbacks.push('mutateAsync.onSettled'),
476 })
477 .catch((error) =>
478 callbacks.push(`mutateAsync.error:${(error as Error).message}`),
479 )
480 await vi.advanceTimersByTimeAsync(30)
481​
482 expect(callbacks).toEqual([
483 'useMutation.onError',
484 'useMutation.onSettled',
485 'mutateAsync.onError',
486 'mutateAsync.onSettled',
487 'mutateAsync.error:oops',
488 ])
489 }),
490 )
491​
492 it(
493 'should recreate observer when queryClient changes',
494 withEffectRoot(async () => {
495 const queryClient1 = new QueryClient()
496 const queryClient2 = new QueryClient()
497​
498 let activeClient = $state(queryClient1)
499​
500 const mutation = createMutation(
501 () => ({
502 mutationFn: (params: string) => sleep(10).then(() => params),
503 }),
504 () => activeClient,
505 )
506​
507 mutation.mutate('first')
508 await vi.advanceTimersByTimeAsync(11)
509​
510 expect(mutation.status).toBe('success')
511 expect(mutation.data).toBe('first')
512​
513 activeClient = queryClient2
514 flushSync()
515​
516 expect(mutation.status).toBe('idle')
517 expect(mutation.data).toBeUndefined()
518 }),
519 )
520​
521 it('should update the cache in onMutate and roll back via onMutateResult in onError', async () => {
522 const key = queryKey()
523 queryClient.setQueryData<Array<string>>(key, ['Todo 1'])
524​
525 const rendered = render(OptimisticUpdate, {
526 props: { queryClient, queryKey: key, shouldSucceed: false },
527 })
528​
529 fireEvent.click(rendered.getByRole('button', { name: /add/i }))
530 // The optimistic value lands after onMutate's first await, so flush
531 // microtasks before asserting.
532 await vi.advanceTimersByTimeAsync(0)
533​
534 expect(queryClient.getQueryData(key)).toEqual(['Todo 1', 'Todo 2'])
535​
536 await vi.advanceTimersByTimeAsync(11)
537​
538 expect(queryClient.getQueryData(key)).toEqual(['Todo 1'])
539 })
540​
541 it('should keep the optimistic update in place when the mutation succeeds', async () => {
542 const key = queryKey()
543 queryClient.setQueryData<Array<string>>(key, ['Todo 1'])
544​
545 const rendered = render(OptimisticUpdate, {
546 props: { queryClient, queryKey: key, shouldSucceed: true },
547 })
548​
549 fireEvent.click(rendered.getByRole('button', { name: /add/i }))
550 await vi.advanceTimersByTimeAsync(11)
551​
552 expect(queryClient.getQueryData(key)).toEqual(['Todo 1', 'Todo 2'])
553 })
554​
555 it('should pass a non-undefined onMutateResult alongside context to onSuccess', async () => {
556 const onSuccessMock = vi.fn()
557​
558 const rendered = render(SuccessContext, {
559 props: { queryClient, onSuccessMock },
560 })
561​
562 fireEvent.click(rendered.getByRole('button', { name: /Mutate/i }))
563 await vi.advanceTimersByTimeAsync(10)
564​
565 expect(onSuccessMock).toHaveBeenCalledTimes(1)
566 const [data, variables, onMutateResult, context] =
567 onSuccessMock.mock.calls[0]!
568 expect(data).toBe('TODO')
569 expect(variables).toBe('todo')
570 expect(onMutateResult).toEqual({ startedWith: 'todo' })
571 expect(context.client).toBe(queryClient)
572 expect(context.meta).toBeUndefined()
573 expect(context.mutationKey).toBeUndefined()
574 })
575​
576 it('should include mutationKey in the context passed to hook-level callbacks', async () => {
577 const onSuccessMock = vi.fn()
578​
579 const rendered = render(SuccessContext, {
580 props: { queryClient, mutationKey: ['todos', 'add'], onSuccessMock },
581 })
582​
583 fireEvent.click(rendered.getByRole('button', { name: /Mutate/i }))
584 await vi.advanceTimersByTimeAsync(10)
585​
586 expect(onSuccessMock).toHaveBeenCalledTimes(1)
587 expect(onSuccessMock.mock.calls[0]?.[3].mutationKey).toEqual([
588 'todos',
589 'add',
590 ])
591 })
592​
593 it('should give mutationFn the same QueryClient instance via context', async () => {
594 const key = queryKey()
595 queryClient.setQueryData(key, 'tag-from-this-client')
596​
597 const rendered = render(MutationFnContext, {
598 props: { queryClient, queryKey: key },
599 })
600​
601 fireEvent.click(rendered.getByRole('button', { name: /Mutate/i }))
602 await vi.advanceTimersByTimeAsync(11)
603​
604 expect(rendered.getByText('data: tag-from-this-client')).toBeInTheDocument()
605 })
606​
607 it('should let onSuccess invalidate queries via context.client without a useQueryClient() closure', async () => {
608 const key = queryKey()
609 queryClient.setQueryData(key, 'data')
610​
611 const rendered = render(InvalidateFromContext, {
612 props: { queryClient, queryKey: key },
613 })
614​
615 expect(queryClient.getQueryState(key)?.isInvalidated).toBe(false)
616​
617 fireEvent.click(rendered.getByRole('button', { name: /Mutate/i }))
618 await vi.advanceTimersByTimeAsync(10)
619​
620 expect(queryClient.getQueryState(key)?.isInvalidated).toBe(true)
621 })
622​
623 it('should give a per-call onSuccess the same QueryClient instance via context', async () => {
624 const perCallOnSuccess = vi.fn()
625​
626 const rendered = render(PerCallSuccess, {
627 props: { queryClient, perCallOnSuccess },
628 })
629​
630 fireEvent.click(rendered.getByRole('button', { name: /Mutate/i }))
631 await vi.advanceTimersByTimeAsync(10)
632​
633 expect(perCallOnSuccess).toHaveBeenCalledTimes(1)
634 expect(perCallOnSuccess.mock.calls[0]?.[3].client).toBe(queryClient)
635 })
636​
637 it('should be able to run multiple mutateAsync calls in parallel with Promise.all', async () => {
638 const rendered = render(ParallelMutateAsync, {
639 props: { queryClient, strategy: 'all' },
640 })
641​
642 fireEvent.click(rendered.getByRole('button', { name: /upload all/i }))
643 await vi.advanceTimersByTimeAsync(11)
644​
645 expect(
646 rendered.getByText(
647 'result: uploaded: file1, uploaded: file2, uploaded: file3',
648 ),
649 ).toBeInTheDocument()
650 })
651​
652 it('should handle Promise.all rejection when one parallel mutateAsync call fails', async () => {
653 const rendered = render(ParallelMutateAsync, {
654 props: { queryClient, strategy: 'all', failOn: 'file2' },
655 })
656​
657 fireEvent.click(rendered.getByRole('button', { name: /upload all/i }))
658 await vi.advanceTimersByTimeAsync(11)
659​
660 expect(
661 rendered.getByText('result: error: upload failed'),
662 ).toBeInTheDocument()
663 })
664​
665 it('should handle partial failure in parallel mutateAsync calls with Promise.allSettled', async () => {
666 const rendered = render(ParallelMutateAsync, {
667 props: { queryClient, strategy: 'allSettled', failOn: 'file2' },
668 })
669​
670 fireEvent.click(rendered.getByRole('button', { name: /upload all/i }))
671 await vi.advanceTimersByTimeAsync(11)
672​
673 expect(
674 rendered.getByText(
675 'result: uploaded: file1, error: upload failed, uploaded: file3',
676 ),
677 ).toBeInTheDocument()
678 })
679​
680 it('should only fire the per-call onSuccess for the last mutate() call', async () => {
681 const onSuccessPerCall = vi.fn()
682​
683 const rendered = render(ConcurrentMutate, {
684 props: { queryClient, onSuccessPerCall },
685 })
686​
687 expect(rendered.getByText('data: null, status: idle')).toBeInTheDocument()
688​
689 fireEvent.click(rendered.getByRole('button', { name: /mutate1/i }))
690 fireEvent.click(rendered.getByRole('button', { name: /mutate2/i }))
691​
692 await vi.advanceTimersByTimeAsync(11)
693​
694 expect(
695 rendered.getByText('data: Todo 2, status: success'),
696 ).toBeInTheDocument()
697​
698 expect(onSuccessPerCall).toHaveBeenCalledTimes(1)
699 expect(onSuccessPerCall).toHaveBeenCalledWith(
700 'Todo 2',
701 'Todo 2',
702 undefined,
703 expect.anything(),
704 )
705 })
706})