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