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

createMutation.svelte.test.ts

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