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

inject-mutation.test.ts

1,070 lines32.2 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 { 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 }))
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 ),
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 }))
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(),
1067 expect(rendered.getByText('data: Todo 2')).toBeInTheDocument()
1068 })
1069 })