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 await vi.advanceTimersByTimeAsync(0)
307 expect(onMutate).toHaveBeenCalledTimes(1)
308 })
309β
310 it('should call onError when passed as an option', async () => {
311 const onError = vi.fn()
312 const mutation = TestBed.runInInjectionContext(() => {
313 return injectMutation(() => ({
314 mutationFn: (_params: string) =>
315 sleep(10).then(() => Promise.reject(new Error('Some error'))),
316 onError,
317 }))
318 })
319β
320 mutation.mutate('')
321 await vi.advanceTimersByTimeAsync(10)
322 expect(onError).toHaveBeenCalledTimes(1)
323 })
324β
325 it('should call onSuccess when passed as an option', async () => {
326 const onSuccess = vi.fn()
327 const mutation = TestBed.runInInjectionContext(() => {
328 return injectMutation(() => ({
329 mutationFn: (params: string) => sleep(10).then(() => params),
330 onSuccess,
331 }))
332 })
333β
334 mutation.mutate('')
335 await vi.advanceTimersByTimeAsync(10)
336 expect(onSuccess).toHaveBeenCalledTimes(1)
337 })
338β
339 it('should call onSettled when passed as an option', async () => {
340 const onSettled = vi.fn()
341 const mutation = TestBed.runInInjectionContext(() => {
342 return injectMutation(() => ({
343 mutationFn: (params: string) => sleep(10).then(() => params),
344 onSettled,
345 }))
346 })
347β
348 mutation.mutate('')
349 await vi.advanceTimersByTimeAsync(10)
350 expect(onSettled).toHaveBeenCalledTimes(1)
351 })
352β
353 it('should call onError when passed as an argument of mutate function', async () => {
354 const onError = vi.fn()
355 const mutation = TestBed.runInInjectionContext(() => {
356 return injectMutation(() => ({
357 mutationFn: (_params: string) =>
358 sleep(10).then(() => Promise.reject(new Error('Some error'))),
359 }))
360 })
361β
362 mutation.mutate('', { onError })
363 await vi.advanceTimersByTimeAsync(10)
364 expect(onError).toHaveBeenCalledTimes(1)
365 })
366β
367 it('should call onSuccess when passed as an argument of mutate function', async () => {
368 const onSuccess = vi.fn()
369 const mutation = TestBed.runInInjectionContext(() => {
370 return injectMutation(() => ({
371 mutationFn: (params: string) => sleep(10).then(() => params),
372 }))
373 })
374β
375 mutation.mutate('', { onSuccess })
376 await vi.advanceTimersByTimeAsync(10)
377 expect(onSuccess).toHaveBeenCalledTimes(1)
378 })
379β
380 it('should call onSettled when passed as an argument of mutate function', async () => {
381 const onSettled = vi.fn()
382 const mutation = TestBed.runInInjectionContext(() => {
383 return injectMutation(() => ({
384 mutationFn: (params: string) => sleep(10).then(() => params),
385 }))
386 })
387β
388 mutation.mutate('', { onSettled })
389 await vi.advanceTimersByTimeAsync(10)
390 expect(onSettled).toHaveBeenCalledTimes(1)
391 })
392β
393 it('should fire both onSettled functions', async () => {
394 const onSettled = vi.fn()
395 const onSettledMutate = vi.fn()
396 const mutation = TestBed.runInInjectionContext(() => {
397 return injectMutation(() => ({
398 mutationFn: (params: string) => sleep(10).then(() => params),
399 onSettled,
400 }))
401 })
402β
403 mutation.mutate('', { onSettled: onSettledMutate })
404 await vi.advanceTimersByTimeAsync(10)
405 expect(onSettled).toHaveBeenCalledTimes(1)
406 expect(onSettledMutate).toHaveBeenCalledTimes(1)
407 })
408β
409 it('should pass a non-undefined onMutateResult alongside context to onSuccess', async () => {
410 const onSuccess = vi.fn()
411 const mutation = TestBed.runInInjectionContext(() => {
412 return injectMutation(() => ({
413 mutationFn: (text: string) =>
414 sleep(10).then(() => text.toUpperCase()),
415 onMutate: (text: string) => ({ startedWith: text }),
416 onSuccess,
417 }))
418 })
419β
420 mutation.mutate('todo')
421 await vi.advanceTimersByTimeAsync(10)
422 expect(onSuccess).toHaveBeenCalledTimes(1)
423 const [data, variables, onMutateResult, context] =
424 onSuccess.mock.calls[0]!
425 expect(data).toBe('TODO')
426 expect(variables).toBe('todo')
427 expect(onMutateResult).toEqual({ startedWith: 'todo' })
428 expect(context.client).toBe(queryClient)
429 expect(context.meta).toBeUndefined()
430 expect(context.mutationKey).toBeUndefined()
431 })
432β
433 it('should give mutationFn the same QueryClient instance via context', async () => {
434 const key = queryKey()
435 queryClient.setQueryData(key, 'tag-from-this-client')
436β
437 @Component({
438 template: `<div>data: {{ mutation.data() ?? 'none' }}</div>`,
439 })
440 class Page {
441 readonly mutation = injectMutation(() => ({
442 mutationFn: (_text: string, context) =>
443 sleep(10).then(() => context.client.getQueryData(key)),
444 }))
445 }
446β
447 const rendered = await render(Page)
448β
449 rendered.fixture.componentInstance.mutation.mutate('todo')
450 await vi.advanceTimersByTimeAsync(11)
451 rendered.fixture.detectChanges()
452 expect(
453 rendered.getByText('data: tag-from-this-client'),
454 ).toBeInTheDocument()
455 })
456β
457 it('should include mutationKey in the context passed to hook-level callbacks', async () => {
458 const onSuccess = vi.fn()
459 const mutation = TestBed.runInInjectionContext(() => {
460 return injectMutation(() => ({
461 mutationKey: ['todos', 'add'],
462 mutationFn: (text: string) => sleep(10).then(() => text),
463 onSuccess,
464 }))
465 })
466β
467 mutation.mutate('todo')
468 await vi.advanceTimersByTimeAsync(10)
469 expect(onSuccess).toHaveBeenCalledTimes(1)
470 expect(onSuccess.mock.calls[0]?.[3].mutationKey).toEqual(['todos', 'add'])
471 })
472β
473 it('should let onSuccess invalidate queries via context.client without an injected QueryClient', async () => {
474 const key = queryKey()
475 queryClient.setQueryData(key, 'data')
476β
477 const mutation = TestBed.runInInjectionContext(() => {
478 return injectMutation(() => ({
479 mutationFn: () => sleep(10).then(() => 'mutated'),
480 onSuccess: (_data, _variables, _onMutateResult, context) => {
481 context.client.invalidateQueries({ queryKey: key })
482 },
483 }))
484 })
485β
486 expect(queryClient.getQueryState(key)?.isInvalidated).toBe(false)
487β
488 mutation.mutate()
489 await vi.advanceTimersByTimeAsync(10)
490 expect(queryClient.getQueryState(key)?.isInvalidated).toBe(true)
491 })
492β
493 it('should give a per-call onSuccess the same QueryClient instance via context', async () => {
494 const onSuccessMutate = vi.fn()
495 const mutation = TestBed.runInInjectionContext(() => {
496 return injectMutation(() => ({
497 mutationFn: (text: string) => sleep(10).then(() => text),
498 }))
499 })
500β
501 mutation.mutate('todo', { onSuccess: onSuccessMutate })
502 await vi.advanceTimersByTimeAsync(10)
503 expect(onSuccessMutate).toHaveBeenCalledTimes(1)
504 expect(onSuccessMutate.mock.calls[0]?.[3].client).toBe(queryClient)
505 })
506 })
507β
508 it('should support required signal inputs', async () => {
509 const mutationCache = queryClient.getMutationCache()
510β
511 @Component({
512 selector: 'app-fake',
513 template: `
514 <button (click)="mutate()"></button>
515 <span>{{ mutation.data() }}</span>
516 `,
517 changeDetection: ChangeDetectionStrategy.OnPush,
518 })
519 class FakeComponent {
520 name = input.required<string>()
521β
522 mutation = injectMutation(() => ({
523 mutationKey: ['fake', this.name()],
524 mutationFn: () => sleep(10).then(() => this.name()),
525 }))
526β
527 mutate(): void {
528 this.mutation.mutate()
529 }
530 }
531β
532 const name = signal('value')
533 const rendered = await render(FakeComponent, {
534 bindings: [inputBinding('name', name.asReadonly())],
535 detectChangesOnRender: false,
536 })
537 rendered.fixture.detectChanges()
538β
539 rendered.getByRole('button').click()
540β
541 await vi.advanceTimersByTimeAsync(11)
542 rendered.fixture.detectChanges()
543β
544 expect(rendered.getByText('value')).toBeInTheDocument()
545 const mutation = mutationCache.find({
546 mutationKey: ['fake', 'value'],
547 })
548 expect(mutation).toBeDefined()
549 expect(mutation!.options.mutationKey).toStrictEqual(['fake', 'value'])
550 })
551β
552 it('should update options on required signal input change', async () => {
553 const mutationCache = queryClient.getMutationCache()
554β
555 @Component({
556 selector: 'app-fake',
557 template: `
558 <button (click)="mutate()"></button>
559 <span>{{ mutation.data() }}</span>
560 `,
561 changeDetection: ChangeDetectionStrategy.OnPush,
562 })
563 class FakeComponent {
564 name = input.required<string>()
565β
566 mutation = injectMutation(() => ({
567 mutationKey: ['fake', this.name()],
568 mutationFn: () => sleep(10).then(() => this.name()),
569 }))
570β
571 mutate(): void {
572 this.mutation.mutate()
573 }
574 }
575β
576 const name = signal('value')
577 const rendered = await render(FakeComponent, {
578 bindings: [inputBinding('name', name.asReadonly())],
579 detectChangesOnRender: false,
580 })
581 rendered.fixture.detectChanges()
582β
583 rendered.getByRole('button').click()
584 await vi.advanceTimersByTimeAsync(11)
585 rendered.fixture.detectChanges()
586β
587 expect(rendered.getByText('value')).toBeInTheDocument()
588β
589 name.set('updatedValue')
590 rendered.fixture.detectChanges()
591β
592 rendered.getByRole('button').click()
593 await vi.advanceTimersByTimeAsync(11)
594 rendered.fixture.detectChanges()
595β
596 expect(rendered.getByText('updatedValue')).toBeInTheDocument()
597β
598 const mutations = mutationCache.findAll()
599 expect(mutations.length).toBe(2)
600 const [mutation1, mutation2] = mutations
601 expect(mutation1!.options.mutationKey).toEqual(['fake', 'value'])
602 expect(mutation2!.options.mutationKey).toEqual(['fake', 'updatedValue'])
603 })
604β
605 describe('injection context', () => {
606 it('throws NG0203 with descriptive error outside injection context', () => {
607 expect(() => {
608 injectMutation(() => ({
609 mutationKey: ['injectionContextError'],
610 mutationFn: () => Promise.resolve(),
611 }))
612 }).toThrowError(/NG0203(.*?)injectMutation/)
613 })
614β
615 it('should complete mutation before whenStable() resolves', async () => {
616 const app = TestBed.inject(ApplicationRef)
617 let mutationStarted = false
618 let mutationCompleted = false
619β
620 const mutation = TestBed.runInInjectionContext(() =>
621 injectMutation(() => ({
622 mutationKey: ['pendingTasksTest'],
623 mutationFn: async (data: string) => {
624 mutationStarted = true
625 await sleep(50)
626 mutationCompleted = true
627 return `processed: ${data}`
628 },
629 })),
630 )
631β
632 expect(mutation.data()).toBeUndefined()
633 expect(mutationStarted).toBe(false)
634β
635 mutation.mutate('test')
636β
637 // Wait for mutation to start and Angular to be "stable"
638 const stablePromise = app.whenStable()
639 await vi.advanceTimersByTimeAsync(60)
640 await stablePromise
641β
642 // After whenStable(), mutation should be complete
643 expect(mutationStarted).toBe(true)
644 expect(mutationCompleted).toBe(true)
645 expect(mutation.isSuccess()).toBe(true)
646 expect(mutation.data()).toBe('processed: test')
647 })
648β
649 it('should handle synchronous mutation with retry', async () => {
650 TestBed.resetTestingModule()
651 TestBed.configureTestingModule({
652 providers: [
653 provideAngularQueryChangeDetection(),
654 provideTanStackQuery(() => queryClient),
655 ],
656 })
657β
658 const app = TestBed.inject(ApplicationRef)
659 let attemptCount = 0
660β
661 const mutation = TestBed.runInInjectionContext(() =>
662 injectMutation(() => ({
663 retry: 2,
664 retryDelay: 0, // No delay for synchronous retry
665 mutationFn: async (data: string) => {
666 attemptCount++
667 if (attemptCount <= 2) {
668 throw new Error(`Sync attempt ${attemptCount} failed`)
669 }
670 return `processed: ${data}`
671 },
672 })),
673 )
674β
675 mutation.mutate('retry-test')
676β
677 // Synchronize pending effects for each retry attempt
678 TestBed.tick()
679 await Promise.resolve()
680 await vi.advanceTimersByTimeAsync(10)
681 TestBed.tick()
682 await Promise.resolve()
683 await vi.advanceTimersByTimeAsync(10)
684 TestBed.tick()
685β
686 const stablePromise = app.whenStable()
687 await Promise.resolve()
688 await vi.advanceTimersByTimeAsync(10)
689 await stablePromise
690 expect(mutation.isSuccess()).toBe(true)
691 expect(mutation.data()).toBe('processed: retry-test')
692 expect(attemptCount).toBe(3) // Initial + 2 retries
693 })
694β
695 it('should handle multiple synchronous mutations on same key', async () => {
696 TestBed.resetTestingModule()
697 TestBed.configureTestingModule({
698 providers: [
699 provideAngularQueryChangeDetection(),
700 provideTanStackQuery(() => queryClient),
701 ],
702 })
703β
704 const app = TestBed.inject(ApplicationRef)
705 let callCount = 0
706β
707 const mutation1 = TestBed.runInInjectionContext(() =>
708 injectMutation(() => ({
709 mutationKey: ['sync-mutation-key'],
710 mutationFn: async (data: string) => {
711 callCount++
712 return `mutation1: ${data}`
713 },
714 })),
715 )
716β
717 const mutation2 = TestBed.runInInjectionContext(() =>
718 injectMutation(() => ({
719 mutationKey: ['sync-mutation-key'],
720 mutationFn: async (data: string) => {
721 callCount++
722 return `mutation2: ${data}`
723 },
724 })),
725 )
726β
727 mutation1.mutate('test1')
728 mutation2.mutate('test2')
729β
730 // Synchronize pending effects
731 TestBed.tick()
732β
733 const stablePromise = app.whenStable()
734 // Flush microtasks to allow TanStack Query's scheduled notifications to process
735 await Promise.resolve()
736 await vi.advanceTimersByTimeAsync(1)
737 await stablePromise
738 expect(mutation1.isSuccess()).toBe(true)
739 expect(mutation1.data()).toBe('mutation1: test1')
740 expect(mutation2.isSuccess()).toBe(true)
741 expect(mutation2.data()).toBe('mutation2: test2')
742 expect(callCount).toBe(2)
743 })
744β
745 it('should handle synchronous mutation with optimistic updates', async () => {
746 TestBed.resetTestingModule()
747 TestBed.configureTestingModule({
748 providers: [
749 provideAngularQueryChangeDetection(),
750 provideTanStackQuery(() => queryClient),
751 ],
752 })
753β
754 const app = TestBed.inject(ApplicationRef)
755 const testQueryKey = ['sync-optimistic']
756 let onMutateCalled = false
757 let onSuccessCalled = false
758 let queryDataInsideOnMutate: string | undefined
759β
760 queryClient.setQueryData(testQueryKey, 'initial')
761β
762 const query = TestBed.runInInjectionContext(() =>
763 injectQuery(() => ({
764 queryKey: testQueryKey,
765 queryFn: () => Promise.resolve('initial'),
766 staleTime: Infinity,
767 })),
768 )
769β
770 const mutation = TestBed.runInInjectionContext(() =>
771 injectMutation(() => ({
772 mutationFn: async (data: string) => {
773 await sleep(50)
774 return `final: ${data}`
775 },
776 onMutate: async (variables) => {
777 onMutateCalled = true
778 queryClient.setQueryData(testQueryKey, `optimistic: ${variables}`)
779 queryDataInsideOnMutate = query.data()
780 },
781 onSuccess: (data) => {
782 onSuccessCalled = true
783 queryClient.setQueryData(testQueryKey, data)
784 },
785 })),
786 )
787β
788 TestBed.tick()
789β
790 expect(queryClient.getQueryData(testQueryKey)).toBe('initial')
791 mutation.mutate('test')
792β
793 // Flush microtasks to allow TanStack Query's scheduled notifications to process
794 await Promise.resolve()
795β
796 // The observed query signal must be current inside the onMutate callback,
797 // immediately after the optimistic cache write.
798 expect(onMutateCalled).toBe(true)
799 expect(queryClient.getQueryData(testQueryKey)).toBe('optimistic: test')
800 expect(queryDataInsideOnMutate).toBe('optimistic: test')
801β
802 // Check stability before the mutation completes, waiting for the next macro task
803 await vi.advanceTimersByTimeAsync(0)
804 expect(mutation.isPending()).toBe(true)
805 expect(await firstValueFrom(app.isStable)).toBe(false)
806β
807 // Wait for the mutation to complete
808 const stablePromise = app.whenStable()
809 await vi.advanceTimersByTimeAsync(60)
810 await stablePromise
811β
812 expect(onSuccessCalled).toBe(true)
813 expect(mutation.isSuccess()).toBe(true)
814 expect(mutation.data()).toBe('final: test')
815 expect(queryClient.getQueryData(testQueryKey)).toBe('final: test')
816 })
817β
818 it('reads an optimistic update inside onMutate before the query signal or effects initialize', async () => {
819 const testQueryKey = ['unread-sync-optimistic']
820 const seenInsideOnMutate: Array<string | undefined> = []
821 queryClient.setQueryData(testQueryKey, 'initial')
822β
823 const query = TestBed.runInInjectionContext(() =>
824 injectQuery(() => ({
825 queryKey: testQueryKey,
826 queryFn: () => Promise.resolve('initial'),
827 staleTime: Infinity,
828 })),
829 )
830 const mutation = TestBed.runInInjectionContext(() =>
831 injectMutation(() => ({
832 mutationFn: async () => 'server',
833 onMutate: () => {
834 queryClient.setQueryData(testQueryKey, 'optimistic')
835 seenInsideOnMutate.push(query.data())
836 },
837 })),
838 )
839β
840 // No signal read and no TestBed.tick() occurs before mutateAsync. The
841 // first query read must still pull the optimistic cache value; its
842 // observer subscription can be committed later.
843 await mutation.mutateAsync()
844β
845 expect(seenInsideOnMutate).toEqual(['optimistic'])
846 })
847β
848 it('should handle synchronous mutation cancellation', async () => {
849 TestBed.resetTestingModule()
850 TestBed.configureTestingModule({
851 providers: [
852 provideAngularQueryChangeDetection(),
853 provideTanStackQuery(() => queryClient),
854 ],
855 })
856β
857 const app = TestBed.inject(ApplicationRef)
858β
859 const mutation = TestBed.runInInjectionContext(() =>
860 injectMutation(() => ({
861 mutationKey: ['cancel-sync'],
862 mutationFn: async (data: string) => `processed: ${data}`, // Synchronous resolution
863 })),
864 )
865β
866 mutation.mutate('test')
867β
868 // Synchronize pending effects
869 TestBed.tick()
870β
871 const stablePromise = app.whenStable()
872 // Flush microtasks to allow TanStack Query's scheduled notifications to process
873 await Promise.resolve()
874 await vi.advanceTimersByTimeAsync(1)
875 await stablePromise
876β
877 // Synchronous mutations complete immediately
878 expect(mutation.isSuccess()).toBe(true)
879 expect(mutation.data()).toBe('processed: test')
880 })
881 })
882β
883 describe('optimistic updates', () => {
884 it('should update the cache in onMutate and roll back via onMutateResult in onError', async () => {
885 const key = queryKey()
886 queryClient.setQueryData<Array<string>>(key, ['Todo 1'])
887β
888 @Component({
889 template: `<div>isError: {{ mutation.isError() }}</div>`,
890 })
891 class Page {
892 readonly mutation = injectMutation(() => ({
893 mutationFn: () =>
894 sleep(10).then(() => Promise.reject(new Error('Some error'))),
895 onMutate: async (newTodo: string) => {
896 await queryClient.cancelQueries({ queryKey: key })
897 const previousTodos = queryClient.getQueryData<Array<string>>(key)
898β
899 queryClient.setQueryData<Array<string>>(key, (old) => [
900 ...(old ?? []),
901 newTodo,
902 ])
903β
904 return { previousTodos }
905 },
906 onError: (_err, _newTodo, onMutateResult) => {
907 queryClient.setQueryData(key, onMutateResult?.previousTodos)
908 },
909 }))
910 }
911β
912 const rendered = await render(Page)
913β
914 rendered.fixture.componentInstance.mutation.mutate('Todo 2')
915 // onMutate runs synchronously up to its first await, so the optimistic
916 // value is visible immediately, before the mutationFn settles.
917 await vi.advanceTimersByTimeAsync(0)
918 expect(queryClient.getQueryData(key)).toEqual(['Todo 1', 'Todo 2'])
919 await vi.advanceTimersByTimeAsync(11)
920 rendered.fixture.detectChanges()
921 expect(rendered.getByText('isError: true')).toBeInTheDocument()
922 expect(queryClient.getQueryData(key)).toEqual(['Todo 1'])
923 })
924β
925 it('should keep the optimistic update in place when the mutation succeeds', async () => {
926 const key = queryKey()
927 queryClient.setQueryData<Array<string>>(key, ['Todo 1'])
928β
929 @Component({
930 template: `<div>isSuccess: {{ mutation.isSuccess() }}</div>`,
931 })
932 class Page {
933 readonly mutation = injectMutation(() => ({
934 mutationFn: (newTodo: string) => sleep(10).then(() => newTodo),
935 onMutate: async (newTodo: string) => {
936 await queryClient.cancelQueries({ queryKey: key })
937 const previousTodos = queryClient.getQueryData<Array<string>>(key)
938β
939 queryClient.setQueryData<Array<string>>(key, (old) => [
940 ...(old ?? []),
941 newTodo,
942 ])
943β
944 return { previousTodos }
945 },
946 onError: (_err, _newTodo, onMutateResult) => {
947 queryClient.setQueryData(key, onMutateResult?.previousTodos)
948 },
949 }))
950 }
951β
952 const rendered = await render(Page)
953β
954 rendered.fixture.componentInstance.mutation.mutate('Todo 2')
955 await vi.advanceTimersByTimeAsync(11)
956 rendered.fixture.detectChanges()
957 expect(rendered.getByText('isSuccess: true')).toBeInTheDocument()
958 expect(queryClient.getQueryData(key)).toEqual(['Todo 1', 'Todo 2'])
959 })
960 })
961β
962 describe('concurrent mutate calls', () => {
963 it('should report each mutateAsync call result independently when some fail', async () => {
964 @Component({
965 template: `<div>isPending: {{ mutation.isPending() }}</div>`,
966 })
967 class Page {
968 readonly mutation = injectMutation(() => ({
969 mutationFn: (todo: string) =>
970 todo === 'bad'
971 ? sleep(10).then(() => Promise.reject(new Error('Some error')))
972 : sleep(10).then(() => todo),
973 }))
974 }
975β
976 const rendered = await render(Page)
977 const todos = ['Todo 1', 'bad', 'Todo 3']
978β
979 expect(rendered.getByText('isPending: false')).toBeInTheDocument()
980β
981 const settledPromise = Promise.allSettled(
982 todos.map((todo) =>
983 rendered.fixture.componentInstance.mutation.mutateAsync(todo),
984 ),
985 )
986 await vi.advanceTimersByTimeAsync(0)
987 rendered.fixture.detectChanges()
988 expect(rendered.getByText('isPending: true')).toBeInTheDocument()
989 await vi.advanceTimersByTimeAsync(11)
990 rendered.fixture.detectChanges()
991 const results = await settledPromise
992β
993 expect(results).toEqual([
994 { status: 'fulfilled', value: 'Todo 1' },
995 { status: 'rejected', reason: Error('Some error') },
996 { status: 'fulfilled', value: 'Todo 3' },
997 ])
998 expect(rendered.getByText('isPending: false')).toBeInTheDocument()
999 })
1000β
1001 it('should only fire the per-call onSuccess for the last mutate() call', async () => {
1002 const onSuccessMutate = vi.fn()
1003β
1004 @Component({
1005 template: `<div>data: {{ mutation.data() ?? 'none' }}</div>`,
1006 })
1007 class Page {
1008 readonly mutation = injectMutation(() => ({
1009 mutationFn: (todo: string) => sleep(10).then(() => todo),
1010 }))
1011 }
1012β
1013 const rendered = await render(Page)
1014β
1015 rendered.fixture.componentInstance.mutation.mutate('Todo 1', {
1016 onSuccess: onSuccessMutate,
1017 })
1018 rendered.fixture.componentInstance.mutation.mutate('Todo 2', {
1019 onSuccess: onSuccessMutate,
1020 })
1021 await vi.advanceTimersByTimeAsync(11)
1022 rendered.fixture.detectChanges()
1023 expect(onSuccessMutate).toHaveBeenCalledTimes(1)
1024 expect(onSuccessMutate).toHaveBeenCalledWith(
1025 'Todo 2',
1026 'Todo 2',
1027 undefined,
1028 expect.anything(),
1029 )
1030 expect(rendered.getByText('data: Todo 2')).toBeInTheDocument()
1031 })
1032 })
1033})