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

inject-mutation.test.ts

1,266 lines39.3 KB

1import {
2 ApplicationRef,
3 ChangeDetectionStrategy,
4 Component,
5 ErrorHandler,
6 effect,
7 input,
8 inputBinding,
9 signal,
10} from '@angular/core'
11import { TestBed } from '@angular/core/testing'
12import { createKey, sleep } from '@tanstack/query-test-utils'
13import { render } from '@testing-library/angular'
14import { firstValueFrom } from 'rxjs'
15import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
16import {
17 QueryClient,
18 injectIsMutating,
19 injectMutation,
20 injectMutationState,
21 injectQuery,
22 noop,
23 provideTanStackQuery,
24} from '..'
25import { expectSignals, provideAngularQueryChangeDetection } from './test-utils'
26import type { MutationFunctionContext } from '@tanstack/query-core'
27​
28describe('injectMutation', () => {
29 let queryClient: QueryClient
30​
31 beforeEach(() => {
32 queryClient = new QueryClient()
33 vi.useFakeTimers()
34 TestBed.configureTestingModule({
35 providers: [
36 provideAngularQueryChangeDetection(),
37 provideTanStackQuery(() => queryClient),
38 ],
39 })
40 })
41​
42 afterEach(() => {
43 vi.useRealTimers()
44 })
45​
46 it('publishes mutation failures to observers and cache signals without global reporting', async () => {
47 vi.useRealTimers()
48 queryClient.setDefaultOptions({ mutations: { throwOnError: true } })
49 const cacheReport = vi.fn<(error: Error) => void>()
50 queryClient.getMutationCache().config.onError = cacheReport
51 const report = vi.spyOn(TestBed.inject(ErrorHandler), 'handleError')
52 const error = new Error('mutation failed')
53 const mutation = TestBed.runInInjectionContext(() =>
54 injectMutation(() => ({
55 mutationFn: async () => {
56 throw error
57 },
58 })),
59 )
60 const count = TestBed.runInInjectionContext(() => injectIsMutating())
61 const states = TestBed.runInInjectionContext(() => injectMutationState())
62 await TestBed.inject(ApplicationRef).whenStable()
63 const promise = mutation.mutateAsync()
64 expect(mutation.status()).toBe('pending')
65 expect(count()).toBe(1)
66 expect(states()[0]?.status).toBe('pending')
67 await expect(promise).rejects.toBe(error)
68 expect(mutation.error()).toBe(error)
69 expect(mutation.status()).toBe('error')
70 expect(count()).toBe(0)
71 expect(states()[0]?.status).toBe('error')
72 expect(cacheReport).toHaveBeenCalledTimes(1)
73 expect(report).not.toHaveBeenCalled()
74 mutation.mutate()
75 await TestBed.inject(ApplicationRef).whenStable()
76 expect(mutation.error()).toBe(error)
77 })
78​
79 it('should be in idle state initially', () => {
80 const mutation = TestBed.runInInjectionContext(() => {
81 return injectMutation(() => ({
82 mutationFn: (params) => sleep(0).then(() => params),
83 }))
84 })
85​
86 expectSignals(mutation, {
87 isIdle: true,
88 isPending: false,
89 isError: false,
90 isSuccess: false,
91 })
92 })
93​
94 it('should change state after invoking mutate', async () => {
95 const result = 'Mock data'
96​
97 const mutation = TestBed.runInInjectionContext(() => {
98 return injectMutation(() => ({
99 mutationFn: (params: string) => sleep(10).then(() => params),
100 }))
101 })
102​
103 TestBed.tick()
104​
105 mutation.mutate(result)
106 await vi.advanceTimersByTimeAsync(0)
107​
108 expectSignals(mutation, {
109 isIdle: false,
110 isPending: true,
111 isError: false,
112 isSuccess: false,
113 data: undefined,
114 error: null,
115 })
116 })
117​
118 it('should return error when request fails', async () => {
119 const mutation = TestBed.runInInjectionContext(() => {
120 return injectMutation(() => ({
121 mutationFn: () =>
122 sleep(10).then(() => Promise.reject(new Error('Some error'))),
123 }))
124 })
125​
126 mutation.mutate()
127​
128 await vi.advanceTimersByTimeAsync(11)
129​
130 expectSignals(mutation, {
131 isIdle: false,
132 isPending: false,
133 isError: true,
134 isSuccess: false,
135 data: undefined,
136 error: Error('Some error'),
137 })
138 })
139​
140 it('should return data when request succeeds', async () => {
141 const result = 'Mock data'
142 const mutation = TestBed.runInInjectionContext(() => {
143 return injectMutation(() => ({
144 mutationFn: (params: string) => sleep(10).then(() => params),
145 }))
146 })
147​
148 mutation.mutate(result)
149​
150 await vi.advanceTimersByTimeAsync(11)
151​
152 expectSignals(mutation, {
153 isIdle: false,
154 isPending: false,
155 isError: false,
156 isSuccess: true,
157 data: result,
158 error: null,
159 })
160 })
161​
162 it('reactive options should update mutation', () => {
163 const mutationCache = queryClient.getMutationCache()
164 // Signal will be updated before the mutation is called
165 // this test confirms that the mutation uses the updated value
166 const mutationKey = signal(['1'])
167 const mutation = TestBed.runInInjectionContext(() => {
168 return injectMutation(() => ({
169 mutationKey: mutationKey(),
170 mutationFn: (params: string) => sleep(0).then(() => params),
171 }))
172 })
173​
174 mutationKey.set(['2'])
175​
176 mutation.mutate('xyz')
177​
178 const mutations = mutationCache.find({ mutationKey: ['2'] })
179​
180 expect(mutations?.options.mutationKey).toStrictEqual(['2'])
181 })
182​
183 it('reflects a mutation started in ngOnInit', async () => {
184 const statusesInsideOnMutate: Array<string> = []
185​
186 @Component({ template: '' })
187 class TestComponent {
188 readonly mutation = injectMutation(() => ({
189 mutationFn: () => sleep(10).then(() => 'done'),
190 onMutate: () => {
191 statusesInsideOnMutate.push(this.mutation.status())
192 },
193 }))
194​
195 ngOnInit() {
196 this.mutation.mutate()
197 }
198 }
199​
200 const fixture = TestBed.createComponent(TestComponent)
201 fixture.detectChanges()
202​
203 expect(statusesInsideOnMutate).toStrictEqual(['pending'])
204 expect(fixture.componentInstance.mutation.status()).toBe('pending')
205​
206 await vi.advanceTimersByTimeAsync(11)
207 TestBed.tick()
208 expect(fixture.componentInstance.mutation.status()).toBe('success')
209 })
210​
211 it('allows cache listeners to read the result while options update', () => {
212 const mutationKey = signal('one')
213 const mutation = TestBed.runInInjectionContext(() =>
214 injectMutation(() => ({
215 mutationKey: ['reentrant-options', mutationKey()],
216 mutationFn: () => Promise.resolve(),
217 })),
218 )
219​
220 mutation.status()
221 TestBed.tick()
222​
223 const readResult = vi.fn<() => 'error' | 'idle' | 'pending' | 'success'>(
224 () => mutation.status(),
225 )
226 const unsubscribe = queryClient.getMutationCache().subscribe((event) => {
227 // setOptions emits synchronously; this read must not re-enter the signal
228 // computation that caused the options update.
229 if (event.type === 'observerOptionsUpdated') readResult()
230 })
231​
232 mutationKey.set('two')
233​
234 expect(() => TestBed.tick()).not.toThrow()
235 expect(readResult).toHaveBeenCalledWith()
236​
237 unsubscribe()
238 })
239​
240 it('does not track mutation state when mutating from a reactive context', async () => {
241 const trigger = signal(false)
242 const runs = vi.fn<() => void>()
243 const mutation = TestBed.runInInjectionContext(() =>
244 injectMutation(() => ({
245 mutationFn: () => sleep(10),
246 })),
247 )
248​
249 TestBed.runInInjectionContext(() =>
250 effect(() => {
251 runs()
252 if (trigger()) mutation.mutate()
253 }),
254 )
255 TestBed.tick()
256 expect(runs).toHaveBeenCalledTimes(1)
257​
258 trigger.set(true)
259 TestBed.tick()
260 expect(runs).toHaveBeenCalledTimes(2)
261​
262 await vi.advanceTimersByTimeAsync(11)
263 TestBed.tick()
264 expect(runs).toHaveBeenCalledTimes(2)
265 })
266​
267 it('should reset state after invoking mutation.reset', async () => {
268 const mutation = TestBed.runInInjectionContext(() => {
269 return injectMutation(() => ({
270 mutationFn: () =>
271 sleep(10).then(() => Promise.reject(new Error('Some error'))),
272 }))
273 })
274​
275 mutation.mutate()
276​
277 await vi.advanceTimersByTimeAsync(11)
278​
279 expect(mutation.isError()).toBe(true)
280​
281 mutation.reset()
282​
283 await vi.advanceTimersByTimeAsync(0)
284​
285 expectSignals(mutation, {
286 isIdle: true,
287 isPending: false,
288 isError: false,
289 isSuccess: false,
290 data: undefined,
291 error: null,
292 })
293 })
294​
295 describe('side effects', () => {
296 beforeEach(() => {
297 vi.clearAllMocks()
298 })
299​
300 it('should call onMutate when passed as an option', async () => {
301 const onMutate =
302 vi.fn<(variables: string, context: MutationFunctionContext) => void>()
303 const mutation = TestBed.runInInjectionContext(() => {
304 return injectMutation(() => ({
305 mutationFn: (params: string) => sleep(10).then(() => params),
306 onMutate,
307 }))
308 })
309​
310 mutation.mutate('')
311 await vi.advanceTimersByTimeAsync(0)
312 expect(onMutate).toHaveBeenCalledTimes(1)
313 })
314​
315 it('should call onError when passed as an option', async () => {
316 const onError =
317 vi.fn<
318 (
319 error: Error,
320 variables: string,
321 onMutateResult: unknown,
322 context: MutationFunctionContext,
323 ) => void
324 >()
325 const mutation = TestBed.runInInjectionContext(() => {
326 return injectMutation(() => ({
327 mutationFn: (_params: string) =>
328 sleep(10).then(() => Promise.reject(new Error('Some error'))),
329 onError,
330 }))
331 })
332​
333 mutation.mutate('')
334 await vi.advanceTimersByTimeAsync(10)
335 expect(onError).toHaveBeenCalledTimes(1)
336 })
337​
338 it('should call onSuccess when passed as an option', async () => {
339 const onSuccess =
340 vi.fn<
341 (
342 data: string,
343 variables: string,
344 onMutateResult: unknown,
345 context: MutationFunctionContext,
346 ) => void
347 >()
348 const mutation = TestBed.runInInjectionContext(() => {
349 return injectMutation(() => ({
350 mutationFn: (params: string) => sleep(10).then(() => params),
351 onSuccess,
352 }))
353 })
354​
355 mutation.mutate('')
356 await vi.advanceTimersByTimeAsync(10)
357 expect(onSuccess).toHaveBeenCalledTimes(1)
358 })
359​
360 it('should call onSettled when passed as an option', async () => {
361 const onSettled =
362 vi.fn<
363 (
364 data: string | undefined,
365 error: Error | null,
366 variables: string,
367 onMutateResult: unknown,
368 context: MutationFunctionContext,
369 ) => void
370 >()
371 const mutation = TestBed.runInInjectionContext(() => {
372 return injectMutation(() => ({
373 mutationFn: (params: string) => sleep(10).then(() => params),
374 onSettled,
375 }))
376 })
377​
378 mutation.mutate('')
379 await vi.advanceTimersByTimeAsync(10)
380 expect(onSettled).toHaveBeenCalledTimes(1)
381 })
382​
383 it('should call onError when passed as an argument of mutate function', async () => {
384 const onError =
385 vi.fn<
386 (
387 error: Error,
388 variables: string,
389 onMutateResult: unknown,
390 context: MutationFunctionContext,
391 ) => void
392 >()
393 const mutation = TestBed.runInInjectionContext(() => {
394 return injectMutation(() => ({
395 mutationFn: (_params: string) =>
396 sleep(10).then(() => Promise.reject(new Error('Some error'))),
397 }))
398 })
399​
400 mutation.mutate('', { onError })
401 await vi.advanceTimersByTimeAsync(10)
402 expect(onError).toHaveBeenCalledTimes(1)
403 })
404​
405 it('should call onSuccess when passed as an argument of mutate function', async () => {
406 const onSuccess =
407 vi.fn<
408 (
409 data: string,
410 variables: string,
411 onMutateResult: unknown,
412 context: MutationFunctionContext,
413 ) => void
414 >()
415 const mutation = TestBed.runInInjectionContext(() => {
416 return injectMutation(() => ({
417 mutationFn: (params: string) => sleep(10).then(() => params),
418 }))
419 })
420​
421 mutation.mutate('', { onSuccess })
422 await vi.advanceTimersByTimeAsync(10)
423 expect(onSuccess).toHaveBeenCalledTimes(1)
424 })
425​
426 it('should call onSettled when passed as an argument of mutate function', async () => {
427 const onSettled =
428 vi.fn<
429 (
430 data: string | undefined,
431 error: Error | null,
432 variables: string,
433 onMutateResult: unknown,
434 context: MutationFunctionContext,
435 ) => void
436 >()
437 const mutation = TestBed.runInInjectionContext(() => {
438 return injectMutation(() => ({
439 mutationFn: (params: string) => sleep(10).then(() => params),
440 }))
441 })
442​
443 mutation.mutate('', { onSettled })
444 await vi.advanceTimersByTimeAsync(10)
445 expect(onSettled).toHaveBeenCalledTimes(1)
446 })
447​
448 it('should fire both onSettled functions', async () => {
449 const onSettled =
450 vi.fn<
451 (
452 data: string | undefined,
453 error: Error | null,
454 variables: string,
455 onMutateResult: unknown,
456 context: MutationFunctionContext,
457 ) => void
458 >()
459 const onSettledMutate =
460 vi.fn<
461 (
462 data: string | undefined,
463 error: Error | null,
464 variables: string,
465 onMutateResult: unknown,
466 context: MutationFunctionContext,
467 ) => void
468 >()
469 const mutation = TestBed.runInInjectionContext(() => {
470 return injectMutation(() => ({
471 mutationFn: (params: string) => sleep(10).then(() => params),
472 onSettled,
473 }))
474 })
475​
476 mutation.mutate('', { onSettled: onSettledMutate })
477 await vi.advanceTimersByTimeAsync(10)
478 expect(onSettled).toHaveBeenCalledTimes(1)
479 expect(onSettledMutate).toHaveBeenCalledTimes(1)
480 })
481​
482 it('should call onSuccess and onSettled when passed as arguments of mutate function', async () => {
483 const callbacks: Array<string> = []
484 const mutation = TestBed.runInInjectionContext(() => {
485 return injectMutation(() => ({
486 mutationFn: (params: string) => sleep(10).then(() => params),
487 }))
488 })
489​
490 mutation.mutate('', {
491 onSuccess: () => callbacks.push('mutate.onSuccess'),
492 onSettled: () => callbacks.push('mutate.onSettled'),
493 })
494 await vi.advanceTimersByTimeAsync(10)
495 expect(callbacks).toStrictEqual(['mutate.onSuccess', 'mutate.onSettled'])
496 })
497​
498 it('should call onError and onSettled when passed as arguments of mutate function', async () => {
499 const callbacks: Array<string> = []
500 const mutation = TestBed.runInInjectionContext(() => {
501 return injectMutation(() => ({
502 mutationFn: (_params: string) =>
503 sleep(10).then(() => Promise.reject(new Error('Some error'))),
504 }))
505 })
506​
507 mutation.mutate('', {
508 onError: () => callbacks.push('mutate.onError'),
509 onSettled: () => callbacks.push('mutate.onSettled'),
510 })
511 await vi.advanceTimersByTimeAsync(10)
512 expect(callbacks).toStrictEqual(['mutate.onError', 'mutate.onSettled'])
513 })
514​
515 it('should call onSuccess and onSettled when passed as arguments of mutateAsync function', async () => {
516 const callbacks: Array<string> = []
517 const mutation = TestBed.runInInjectionContext(() => {
518 return injectMutation(() => ({
519 mutationFn: (params: string) => sleep(10).then(() => params),
520 }))
521 })
522​
523 mutation.mutateAsync('', {
524 onSuccess: () => callbacks.push('mutateAsync.onSuccess'),
525 onSettled: () => callbacks.push('mutateAsync.onSettled'),
526 })
527 await vi.advanceTimersByTimeAsync(10)
528 expect(callbacks).toStrictEqual([
529 'mutateAsync.onSuccess',
530 'mutateAsync.onSettled',
531 ])
532 })
533​
534 it('should call onError and onSettled when passed as arguments of mutateAsync function', async () => {
535 const callbacks: Array<string> = []
536 const mutation = TestBed.runInInjectionContext(() => {
537 return injectMutation(() => ({
538 mutationFn: (_params: string) =>
539 sleep(10).then(() => Promise.reject(new Error('Some error'))),
540 }))
541 })
542​
543 mutation
544 .mutateAsync('', {
545 onError: () => callbacks.push('mutateAsync.onError'),
546 onSettled: () => callbacks.push('mutateAsync.onSettled'),
547 })
548 .catch(noop)
549 await vi.advanceTimersByTimeAsync(10)
550 expect(callbacks).toStrictEqual([
551 'mutateAsync.onError',
552 'mutateAsync.onSettled',
553 ])
554 })
555​
556 it('should call onSuccess when passed as an argument of mutateAsync function', async () => {
557 const callbacks: Array<string> = []
558 const mutation = TestBed.runInInjectionContext(() => {
559 return injectMutation(() => ({
560 mutationFn: (params: string) => sleep(10).then(() => params),
561 }))
562 })
563​
564 mutation.mutateAsync('', {
565 onSuccess: () => callbacks.push('mutateAsync.onSuccess'),
566 })
567 await vi.advanceTimersByTimeAsync(10)
568 expect(callbacks).toStrictEqual(['mutateAsync.onSuccess'])
569 })
570​
571 it('should call onError when passed as an argument of mutateAsync function', async () => {
572 const callbacks: Array<string> = []
573 const mutation = TestBed.runInInjectionContext(() => {
574 return injectMutation(() => ({
575 mutationFn: (_params: string) =>
576 sleep(10).then(() => Promise.reject(new Error('Some error'))),
577 }))
578 })
579​
580 mutation
581 .mutateAsync('', {
582 onError: () => callbacks.push('mutateAsync.onError'),
583 })
584 .catch(noop)
585 await vi.advanceTimersByTimeAsync(10)
586 expect(callbacks).toStrictEqual(['mutateAsync.onError'])
587 })
588​
589 it('should call onSettled when passed as an argument of mutateAsync function', async () => {
590 const callbacks: Array<string> = []
591 const mutation = TestBed.runInInjectionContext(() => {
592 return injectMutation(() => ({
593 mutationFn: (params: string) => sleep(10).then(() => params),
594 }))
595 })
596​
597 mutation.mutateAsync('', {
598 onSettled: () => callbacks.push('mutateAsync.onSettled'),
599 })
600 await vi.advanceTimersByTimeAsync(10)
601 expect(callbacks).toStrictEqual(['mutateAsync.onSettled'])
602 })
603​
604 it('should pass a non-undefined onMutateResult alongside context to onSuccess', async () => {
605 const onSuccess =
606 vi.fn<
607 (
608 data: string,
609 variables: string,
610 onMutateResult: unknown,
611 context: MutationFunctionContext,
612 ) => void
613 >()
614 const mutation = TestBed.runInInjectionContext(() => {
615 return injectMutation(() => ({
616 mutationFn: (text: string) =>
617 sleep(10).then(() => text.toUpperCase()),
618 onMutate: (text: string) => ({ startedWith: text }),
619 onSuccess,
620 }))
621 })
622​
623 mutation.mutate('todo')
624 await vi.advanceTimersByTimeAsync(10)
625 expect(onSuccess).toHaveBeenCalledTimes(1)
626 const [data, variables, onMutateResult, context] =
627 onSuccess.mock.calls[0]!
628 expect(data).toBe('TODO')
629 expect(variables).toBe('todo')
630 expect(onMutateResult).toStrictEqual({ startedWith: 'todo' })
631 expect(context.client).toBe(queryClient)
632 expect(context.meta).toBeUndefined()
633 expect(context.mutationKey).toBeUndefined()
634 })
635​
636 it('should give mutationFn the same QueryClient instance via context', async () => {
637 const key = createKey()
638 queryClient.setQueryData(key, 'tag-from-this-client')
639​
640 @Component({
641 template: `<div>data: {{ mutation.data() ?? 'none' }}</div>`,
642 })
643 class Page {
644 readonly mutation = injectMutation(() => ({
645 mutationFn: (_text: string, context) =>
646 sleep(10).then(() => context.client.getQueryData(key)),
647 }))
648 }
649​
650 const rendered = await render(Page)
651​
652 rendered.fixture.componentInstance.mutation.mutate('todo')
653 await vi.advanceTimersByTimeAsync(11)
654 rendered.fixture.detectChanges()
655 expect(
656 rendered.getByText('data: tag-from-this-client'),
657 ).toBeInTheDocument()
658 })
659​
660 it('should include mutationKey in the context passed to hook-level callbacks', async () => {
661 const onSuccess =
662 vi.fn<
663 (
664 data: string,
665 variables: string,
666 onMutateResult: unknown,
667 context: MutationFunctionContext,
668 ) => void
669 >()
670 const mutation = TestBed.runInInjectionContext(() => {
671 return injectMutation(() => ({
672 mutationKey: ['todos', 'add'],
673 mutationFn: (text: string) => sleep(10).then(() => text),
674 onSuccess,
675 }))
676 })
677​
678 mutation.mutate('todo')
679 await vi.advanceTimersByTimeAsync(10)
680 expect(onSuccess).toHaveBeenCalledTimes(1)
681 expect(onSuccess.mock.calls[0]?.[3].mutationKey).toStrictEqual([
682 'todos',
683 'add',
684 ])
685 })
686​
687 it('should let onSuccess invalidate queries via context.client without an injected QueryClient', async () => {
688 const key = createKey()
689 queryClient.setQueryData(key, 'data')
690​
691 const mutation = TestBed.runInInjectionContext(() => {
692 return injectMutation(() => ({
693 mutationFn: () => sleep(10).then(() => 'mutated'),
694 onSuccess: (_data, _variables, _onMutateResult, context) => {
695 context.client.invalidateQueries({ queryKey: key })
696 },
697 }))
698 })
699​
700 expect(queryClient.getQueryState(key)?.isInvalidated).toBe(false)
701​
702 mutation.mutate()
703 await vi.advanceTimersByTimeAsync(10)
704 expect(queryClient.getQueryState(key)?.isInvalidated).toBe(true)
705 })
706​
707 it('should give a per-call onSuccess the same QueryClient instance via context', async () => {
708 const onSuccessMutate =
709 vi.fn<
710 (
711 data: string,
712 variables: string,
713 onMutateResult: unknown,
714 context: MutationFunctionContext,
715 ) => void
716 >()
717 const mutation = TestBed.runInInjectionContext(() => {
718 return injectMutation(() => ({
719 mutationFn: (text: string) => sleep(10).then(() => text),
720 }))
721 })
722​
723 mutation.mutate('todo', { onSuccess: onSuccessMutate })
724 await vi.advanceTimersByTimeAsync(10)
725 expect(onSuccessMutate).toHaveBeenCalledTimes(1)
726 expect(onSuccessMutate.mock.calls[0]?.[3].client).toBe(queryClient)
727 })
728 })
729​
730 it('should support required signal inputs', async () => {
731 const mutationCache = queryClient.getMutationCache()
732​
733 @Component({
734 selector: 'app-fake',
735 template: `
736 <button (click)="mutate()"></button>
737 <span>{{ mutation.data() }}</span>
738 `,
739 changeDetection: ChangeDetectionStrategy.OnPush,
740 })
741 class FakeComponent {
742 name = input.required<string>()
743​
744 mutation = injectMutation(() => ({
745 mutationKey: ['fake', this.name()],
746 mutationFn: () => sleep(10).then(() => this.name()),
747 }))
748​
749 mutate(): void {
750 this.mutation.mutate()
751 }
752 }
753​
754 const name = signal('value')
755 const rendered = await render(FakeComponent, {
756 bindings: [inputBinding('name', name.asReadonly())],
757 detectChangesOnRender: false,
758 })
759 rendered.fixture.detectChanges()
760​
761 rendered.getByRole('button').click()
762​
763 await vi.advanceTimersByTimeAsync(11)
764 rendered.fixture.detectChanges()
765​
766 expect(rendered.getByText('value')).toBeInTheDocument()
767 const mutation = mutationCache.find({
768 mutationKey: ['fake', 'value'],
769 })
770 expect(mutation).toBeDefined()
771 expect(mutation!.options.mutationKey).toStrictEqual(['fake', 'value'])
772 })
773​
774 it('should update options on required signal input change', async () => {
775 const mutationCache = queryClient.getMutationCache()
776​
777 @Component({
778 selector: 'app-fake',
779 template: `
780 <button (click)="mutate()"></button>
781 <span>{{ mutation.data() }}</span>
782 `,
783 changeDetection: ChangeDetectionStrategy.OnPush,
784 })
785 class FakeComponent {
786 name = input.required<string>()
787​
788 mutation = injectMutation(() => ({
789 mutationKey: ['fake', this.name()],
790 mutationFn: () => sleep(10).then(() => this.name()),
791 }))
792​
793 mutate(): void {
794 this.mutation.mutate()
795 }
796 }
797​
798 const name = signal('value')
799 const rendered = await render(FakeComponent, {
800 bindings: [inputBinding('name', name.asReadonly())],
801 detectChangesOnRender: false,
802 })
803 rendered.fixture.detectChanges()
804​
805 rendered.getByRole('button').click()
806 await vi.advanceTimersByTimeAsync(11)
807 rendered.fixture.detectChanges()
808​
809 expect(rendered.getByText('value')).toBeInTheDocument()
810​
811 name.set('updatedValue')
812 rendered.fixture.detectChanges()
813​
814 rendered.getByRole('button').click()
815 await vi.advanceTimersByTimeAsync(11)
816 rendered.fixture.detectChanges()
817​
818 expect(rendered.getByText('updatedValue')).toBeInTheDocument()
819​
820 const mutations = mutationCache.findAll()
821 expect(mutations).toHaveLength(2)
822 const [mutation1, mutation2] = mutations
823 expect(mutation1!.options.mutationKey).toStrictEqual(['fake', 'value'])
824 expect(mutation2!.options.mutationKey).toStrictEqual([
825 'fake',
826 'updatedValue',
827 ])
828 })
829​
830 describe('injection context', () => {
831 it('throws NG0203 with descriptive error outside injection context', () => {
832 expect(() => {
833 injectMutation(() => ({
834 mutationKey: ['injectionContextError'],
835 mutationFn: () => Promise.resolve(),
836 }))
837 }).toThrow(/NG0203(.*?)injectMutation/)
838 })
839​
840 it('should complete mutation before whenStable() resolves', async () => {
841 const app = TestBed.inject(ApplicationRef)
842 let mutationStarted = false
843 let mutationCompleted = false
844​
845 const mutation = TestBed.runInInjectionContext(() =>
846 injectMutation(() => ({
847 mutationKey: ['pendingTasksTest'],
848 mutationFn: async (data: string) => {
849 mutationStarted = true
850 await sleep(50)
851 mutationCompleted = true
852 return `processed: ${data}`
853 },
854 })),
855 )
856​
857 expect(mutation.data()).toBeUndefined()
858 expect(mutationStarted).toBe(false)
859​
860 mutation.mutate('test')
861​
862 // Wait for mutation to start and Angular to be "stable"
863 const stablePromise = app.whenStable()
864 await vi.advanceTimersByTimeAsync(60)
865 await stablePromise
866​
867 // After whenStable(), mutation should be complete
868 expect(mutationStarted).toBe(true)
869 expect(mutationCompleted).toBe(true)
870 expect(mutation.isSuccess()).toBe(true)
871 expect(mutation.data()).toBe('processed: test')
872 })
873​
874 it('should handle synchronous mutation with retry', async () => {
875 TestBed.resetTestingModule()
876 TestBed.configureTestingModule({
877 providers: [
878 provideAngularQueryChangeDetection(),
879 provideTanStackQuery(() => queryClient),
880 ],
881 })
882​
883 const app = TestBed.inject(ApplicationRef)
884 let attemptCount = 0
885​
886 const mutation = TestBed.runInInjectionContext(() =>
887 injectMutation(() => ({
888 retry: 2,
889 retryDelay: 0, // No delay for synchronous retry
890 mutationFn: async (data: string) => {
891 attemptCount++
892 if (attemptCount <= 2) {
893 throw new Error(`Sync attempt ${attemptCount} failed`)
894 }
895 return `processed: ${data}`
896 },
897 })),
898 )
899​
900 mutation.mutate('retry-test')
901​
902 // Synchronize pending effects for each retry attempt
903 TestBed.tick()
904 await Promise.resolve()
905 await vi.advanceTimersByTimeAsync(10)
906 TestBed.tick()
907 await Promise.resolve()
908 await vi.advanceTimersByTimeAsync(10)
909 TestBed.tick()
910​
911 const stablePromise = app.whenStable()
912 await Promise.resolve()
913 await vi.advanceTimersByTimeAsync(10)
914 await stablePromise
915 expect(mutation.isSuccess()).toBe(true)
916 expect(mutation.data()).toBe('processed: retry-test')
917 expect(attemptCount).toBe(3) // Initial + 2 retries
918 })
919​
920 it('should handle multiple synchronous mutations on same key', async () => {
921 TestBed.resetTestingModule()
922 TestBed.configureTestingModule({
923 providers: [
924 provideAngularQueryChangeDetection(),
925 provideTanStackQuery(() => queryClient),
926 ],
927 })
928​
929 const app = TestBed.inject(ApplicationRef)
930 let callCount = 0
931​
932 const mutation1 = TestBed.runInInjectionContext(() =>
933 injectMutation(() => ({
934 mutationKey: ['sync-mutation-key'],
935 mutationFn: async (data: string) => {
936 callCount++
937 return `mutation1: ${data}`
938 },
939 })),
940 )
941​
942 const mutation2 = TestBed.runInInjectionContext(() =>
943 injectMutation(() => ({
944 mutationKey: ['sync-mutation-key'],
945 mutationFn: async (data: string) => {
946 callCount++
947 return `mutation2: ${data}`
948 },
949 })),
950 )
951​
952 mutation1.mutate('test1')
953 mutation2.mutate('test2')
954​
955 // Synchronize pending effects
956 TestBed.tick()
957​
958 const stablePromise = app.whenStable()
959 // Flush microtasks to allow TanStack Query's scheduled notifications to process
960 await Promise.resolve()
961 await vi.advanceTimersByTimeAsync(1)
962 await stablePromise
963 expect(mutation1.isSuccess()).toBe(true)
964 expect(mutation1.data()).toBe('mutation1: test1')
965 expect(mutation2.isSuccess()).toBe(true)
966 expect(mutation2.data()).toBe('mutation2: test2')
967 expect(callCount).toBe(2)
968 })
969​
970 it('should handle synchronous mutation with optimistic updates', async () => {
971 TestBed.resetTestingModule()
972 TestBed.configureTestingModule({
973 providers: [
974 provideAngularQueryChangeDetection(),
975 provideTanStackQuery(() => queryClient),
976 ],
977 })
978​
979 const app = TestBed.inject(ApplicationRef)
980 const testQueryKey = ['sync-optimistic']
981 let onMutateCalled = false
982 let onSuccessCalled = false
983 let queryDataInsideOnMutate: string | undefined
984​
985 queryClient.setQueryData(testQueryKey, 'initial')
986​
987 const query = TestBed.runInInjectionContext(() =>
988 injectQuery(() => ({
989 queryKey: testQueryKey,
990 queryFn: () => Promise.resolve('initial'),
991 staleTime: Infinity,
992 })),
993 )
994​
995 const mutation = TestBed.runInInjectionContext(() =>
996 injectMutation(() => ({
997 mutationFn: async (data: string) => {
998 await sleep(50)
999 return `final: ${data}`
1000 },
1001 onMutate: async (variables) => {
1002 onMutateCalled = true
1003 queryClient.setQueryData(testQueryKey, `optimistic: ${variables}`)
1004 queryDataInsideOnMutate = query.data()
1005 },
1006 onSuccess: (data) => {
1007 onSuccessCalled = true
1008 queryClient.setQueryData(testQueryKey, data)
1009 },
1010 })),
1012​
1013 TestBed.tick()
1014​
1015 expect(queryClient.getQueryData(testQueryKey)).toBe('initial')
1016 mutation.mutate('test')
1017​
1018 // Flush microtasks to allow TanStack Query's scheduled notifications to process
1019 await Promise.resolve()
1020​
1021 // The observed query signal must be current inside the onMutate callback,
1022 // immediately after the optimistic cache write.
1023 expect(onMutateCalled).toBe(true)
1024 expect(queryClient.getQueryData(testQueryKey)).toBe('optimistic: test')
1025 expect(queryDataInsideOnMutate).toBe('optimistic: test')
1026​
1027 // Check stability before the mutation completes, waiting for the next macro task
1028 await vi.advanceTimersByTimeAsync(0)
1029 expect(mutation.isPending()).toBe(true)
1030 await expect(firstValueFrom(app.isStable)).resolves.toBe(false)
1031​
1032 // Wait for the mutation to complete
1033 const stablePromise = app.whenStable()
1034 await vi.advanceTimersByTimeAsync(60)
1035 await stablePromise
1036​
1037 expect(onSuccessCalled).toBe(true)
1038 expect(mutation.isSuccess()).toBe(true)
1039 expect(mutation.data()).toBe('final: test')
1040 expect(queryClient.getQueryData(testQueryKey)).toBe('final: test')
1041 })
1042​
1043 it('reads an optimistic update inside onMutate before the query signal or effects initialize', async () => {
1044 const testQueryKey = ['unread-sync-optimistic']
1045 const seenInsideOnMutate: Array<string | undefined> = []
1046 queryClient.setQueryData(testQueryKey, 'initial')
1047​
1048 const query = TestBed.runInInjectionContext(() =>
1049 injectQuery(() => ({
1050 queryKey: testQueryKey,
1051 queryFn: () => Promise.resolve('initial'),
1052 staleTime: Infinity,
1053 })),
1055 const mutation = TestBed.runInInjectionContext(() =>
1056 injectMutation(() => ({
1057 mutationFn: async () => 'server',
1058 onMutate: () => {
1059 queryClient.setQueryData(testQueryKey, 'optimistic')
1060 seenInsideOnMutate.push(query.data())
1061 },
1062 })),
1064​
1065 // No signal read and no TestBed.tick() occurs before mutateAsync. The
1066 // first query read must still pull the optimistic cache value; its
1067 // observer subscription can be committed later.
1068 await mutation.mutateAsync()
1069​
1070 expect(seenInsideOnMutate).toStrictEqual(['optimistic'])
1071 })
1072​
1073 it('should handle synchronous mutation cancellation', async () => {
1074 TestBed.resetTestingModule()
1075 TestBed.configureTestingModule({
1076 providers: [
1077 provideAngularQueryChangeDetection(),
1078 provideTanStackQuery(() => queryClient),
1079 ],
1080 })
1081​
1082 const app = TestBed.inject(ApplicationRef)
1083​
1084 const mutation = TestBed.runInInjectionContext(() =>
1085 injectMutation(() => ({
1086 mutationKey: ['cancel-sync'],
1087 mutationFn: async (data: string) => `processed: ${data}`, // Synchronous resolution
1088 })),
1090​
1091 mutation.mutate('test')
1092​
1093 // Synchronize pending effects
1094 TestBed.tick()
1095​
1096 const stablePromise = app.whenStable()
1097 // Flush microtasks to allow TanStack Query's scheduled notifications to process
1098 await Promise.resolve()
1099 await vi.advanceTimersByTimeAsync(1)
1100 await stablePromise
1101​
1102 // Synchronous mutations complete immediately
1103 expect(mutation.isSuccess()).toBe(true)
1104 expect(mutation.data()).toBe('processed: test')
1105 })
1106 })
1107​
1108 describe('optimistic updates', () => {
1109 it('should update the cache in onMutate and roll back via onMutateResult in onError', async () => {
1110 const key = createKey()
1111 queryClient.setQueryData<Array<string>>(key, ['Todo 1'])
1112​
1113 @Component({
1114 template: `<div>isError: {{ mutation.isError() }}</div>`,
1115 })
1116 class Page {
1117 readonly mutation = injectMutation(() => ({
1118 mutationFn: () =>
1119 sleep(10).then(() => Promise.reject(new Error('Some error'))),
1120 onMutate: async (newTodo: string) => {
1121 await queryClient.cancelQueries({ queryKey: key })
1122 const previousTodos = queryClient.getQueryData<Array<string>>(key)
1123​
1124 queryClient.setQueryData<Array<string>>(key, (old) => [
1125 ...(old ?? []),
1126 newTodo,
1127 ])
1128​
1129 return { previousTodos }
1130 },
1131 onError: (_err, _newTodo, onMutateResult) => {
1132 queryClient.setQueryData(key, onMutateResult?.previousTodos)
1133 },
1134 }))
1136​
1137 const rendered = await render(Page)
1138​
1139 rendered.fixture.componentInstance.mutation.mutate('Todo 2')
1140 // onMutate runs synchronously up to its first await, so the optimistic
1141 // value is visible immediately, before the mutationFn settles.
1142 await vi.advanceTimersByTimeAsync(0)
1143 expect(queryClient.getQueryData(key)).toStrictEqual(['Todo 1', 'Todo 2'])
1144 await vi.advanceTimersByTimeAsync(11)
1145 rendered.fixture.detectChanges()
1146 expect(rendered.getByText('isError: true')).toBeInTheDocument()
1147 expect(queryClient.getQueryData(key)).toStrictEqual(['Todo 1'])
1148 })
1149​
1150 it('should keep the optimistic update in place when the mutation succeeds', async () => {
1151 const key = createKey()
1152 queryClient.setQueryData<Array<string>>(key, ['Todo 1'])
1153​
1154 @Component({
1155 template: `<div>isSuccess: {{ mutation.isSuccess() }}</div>`,
1156 })
1157 class Page {
1158 readonly mutation = injectMutation(() => ({
1159 mutationFn: (newTodo: string) => sleep(10).then(() => newTodo),
1160 onMutate: async (newTodo: string) => {
1161 await queryClient.cancelQueries({ queryKey: key })
1162 const previousTodos = queryClient.getQueryData<Array<string>>(key)
1163​
1164 queryClient.setQueryData<Array<string>>(key, (old) => [
1165 ...(old ?? []),
1166 newTodo,
1167 ])
1168​
1169 return { previousTodos }
1170 },
1171 onError: (_err, _newTodo, onMutateResult) => {
1172 queryClient.setQueryData(key, onMutateResult?.previousTodos)
1173 },
1174 }))
1176​
1177 const rendered = await render(Page)
1178​
1179 rendered.fixture.componentInstance.mutation.mutate('Todo 2')
1180 await vi.advanceTimersByTimeAsync(11)
1181 rendered.fixture.detectChanges()
1182 expect(rendered.getByText('isSuccess: true')).toBeInTheDocument()
1183 expect(queryClient.getQueryData(key)).toStrictEqual(['Todo 1', 'Todo 2'])
1184 })
1185 })
1186​
1187 describe('concurrent mutate calls', () => {
1188 it('should report each mutateAsync call result independently when some fail', async () => {
1189 @Component({
1190 template: `<div>isPending: {{ mutation.isPending() }}</div>`,
1191 })
1192 class Page {
1193 readonly mutation = injectMutation(() => ({
1194 mutationFn: (todo: string) =>
1195 todo === 'bad'
1196 ? sleep(10).then(() => Promise.reject(new Error('Some error')))
1197 : sleep(10).then(() => todo),
1198 }))
1200​
1201 const rendered = await render(Page)
1202 const todos = ['Todo 1', 'bad', 'Todo 3']
1203​
1204 expect(rendered.getByText('isPending: false')).toBeInTheDocument()
1205​
1206 const settledPromise = Promise.allSettled(
1207 todos.map((todo) =>
1208 rendered.fixture.componentInstance.mutation.mutateAsync(todo),
1209 ),
1211 await vi.advanceTimersByTimeAsync(0)
1212 rendered.fixture.detectChanges()
1213 expect(rendered.getByText('isPending: true')).toBeInTheDocument()
1214 await vi.advanceTimersByTimeAsync(11)
1215 rendered.fixture.detectChanges()
1216 const results = await settledPromise
1217​
1218 expect(results).toStrictEqual([
1219 { status: 'fulfilled', value: 'Todo 1' },
1220 { status: 'rejected', reason: Error('Some error') },
1221 { status: 'fulfilled', value: 'Todo 3' },
1222 ])
1223 expect(rendered.getByText('isPending: false')).toBeInTheDocument()
1224 })
1225​
1226 it('should only fire the per-call onSuccess for the last mutate() call', async () => {
1227 const onSuccessMutate =
1228 vi.fn<
1230 data: string,
1231 variables: string,
1232 onMutateResult: unknown,
1233 context: MutationFunctionContext,
1234 ) => void
1235 >()
1236​
1237 @Component({
1238 template: `<div>data: {{ mutation.data() ?? 'none' }}</div>`,
1239 })
1240 class Page {
1241 readonly mutation = injectMutation(() => ({
1242 mutationFn: (todo: string) => sleep(10).then(() => todo),
1243 }))
1245​
1246 const rendered = await render(Page)
1247​
1248 rendered.fixture.componentInstance.mutation.mutate('Todo 1', {
1249 onSuccess: onSuccessMutate,
1250 })
1251 rendered.fixture.componentInstance.mutation.mutate('Todo 2', {
1252 onSuccess: onSuccessMutate,
1253 })
1254 await vi.advanceTimersByTimeAsync(11)
1255 rendered.fixture.detectChanges()
1256 expect(onSuccessMutate).toHaveBeenCalledTimes(1)
1257 expect(onSuccessMutate).toHaveBeenCalledWith(
1258 'Todo 2',
1259 'Todo 2',
1260 undefined,
1261 expect.anything(),
1263 expect(rendered.getByText('data: Todo 2')).toBeInTheDocument()
1264 })
1265 })