Open History to see the last commit
1import {
2 ApplicationRef,
3 ChangeDetectionStrategy,
4 Component,
5 Injector,
6 NgZone,
7 input,
8 provideZonelessChangeDetection,
9 signal,
10} from '@angular/core'
11import { TestBed } from '@angular/core/testing'
12import { sleep } from '@tanstack/query-test-utils'
13import { firstValueFrom } from 'rxjs'
14import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
15import { QueryClient, injectMutation, provideTanStackQuery } from '..'
16import { expectSignals, registerSignalInput } from './test-utils'
17β
18describe('injectMutation', () => {
19 let queryClient: QueryClient
20β
21 beforeEach(() => {
22 queryClient = new QueryClient()
23 vi.useFakeTimers()
24 TestBed.configureTestingModule({
25 providers: [
26 provideZonelessChangeDetection(),
27 provideTanStackQuery(queryClient),
28 ],
29 })
30 })
31β
32 afterEach(() => {
33 vi.useRealTimers()
34 })
35β
36 test('should be in idle state initially', () => {
37 const mutation = TestBed.runInInjectionContext(() => {
38 return injectMutation(() => ({
39 mutationFn: (params) => sleep(0).then(() => params),
40 }))
41 })
42β
43 expectSignals(mutation, {
44 isIdle: true,
45 isPending: false,
46 isError: false,
47 isSuccess: false,
48 })
49 })
50β
51 test('should change state after invoking mutate', async () => {
52 const result = 'Mock data'
53β
54 const mutation = TestBed.runInInjectionContext(() => {
55 return injectMutation(() => ({
56 mutationFn: (params: string) => sleep(10).then(() => params),
57 }))
58 })
59β
60 TestBed.tick()
61β
62 mutation.mutate(result)
63 await vi.advanceTimersByTimeAsync(0)
64β
65 expectSignals(mutation, {
66 isIdle: false,
67 isPending: true,
68 isError: false,
69 isSuccess: false,
70 data: undefined,
71 error: null,
72 })
73 })
74β
75 test('should return error when request fails', async () => {
76 const mutation = TestBed.runInInjectionContext(() => {
77 return injectMutation(() => ({
78 mutationFn: () =>
79 sleep(10).then(() => Promise.reject(new Error('Some error'))),
80 }))
81 })
82β
83 mutation.mutate()
84β
85 await vi.advanceTimersByTimeAsync(11)
86β
87 expectSignals(mutation, {
88 isIdle: false,
89 isPending: false,
90 isError: true,
91 isSuccess: false,
92 data: undefined,
93 error: Error('Some error'),
94 })
95 })
96β
97 test('should return data when request succeeds', async () => {
98 const result = 'Mock data'
99 const mutation = TestBed.runInInjectionContext(() => {
100 return injectMutation(() => ({
101 mutationFn: (params: string) => sleep(10).then(() => params),
102 }))
103 })
104β
105 mutation.mutate(result)
106β
107 await vi.advanceTimersByTimeAsync(11)
108β
109 expectSignals(mutation, {
110 isIdle: false,
111 isPending: false,
112 isError: false,
113 isSuccess: true,
114 data: result,
115 error: null,
116 })
117 })
118β
119 test('reactive options should update mutation', () => {
120 const mutationCache = queryClient.getMutationCache()
121 // Signal will be updated before the mutation is called
122 // this test confirms that the mutation uses the updated value
123 const mutationKey = signal(['1'])
124 const mutation = TestBed.runInInjectionContext(() => {
125 return injectMutation(() => ({
126 mutationKey: mutationKey(),
127 mutationFn: (params: string) => sleep(0).then(() => params),
128 }))
129 })
130β
131 mutationKey.set(['2'])
132β
133 mutation.mutate('xyz')
134β
135 const mutations = mutationCache.find({ mutationKey: ['2'] })
136β
137 expect(mutations?.options.mutationKey).toEqual(['2'])
138 })
139β
140 test('should reset state after invoking mutation.reset', async () => {
141 const mutation = TestBed.runInInjectionContext(() => {
142 return injectMutation(() => ({
143 mutationFn: () =>
144 sleep(10).then(() => Promise.reject(new Error('Some error'))),
145 }))
146 })
147β
148 mutation.mutate()
149β
150 await vi.advanceTimersByTimeAsync(11)
151β
152 expect(mutation.isError()).toBe(true)
153β
154 mutation.reset()
155β
156 await vi.advanceTimersByTimeAsync(0)
157β
158 expectSignals(mutation, {
159 isIdle: true,
160 isPending: false,
161 isError: false,
162 isSuccess: false,
163 data: undefined,
164 error: null,
165 })
166 })
167β
168 describe('side effects', () => {
169 beforeEach(() => {
170 vi.clearAllMocks()
171 })
172β
173 test('should call onMutate when passed as an option', async () => {
174 const onMutate = vi.fn()
175 const mutation = TestBed.runInInjectionContext(() => {
176 return injectMutation(() => ({
177 mutationFn: (params: string) => sleep(10).then(() => params),
178 onMutate,
179 }))
180 })
181β
182 mutation.mutate('')
183β
184 await vi.advanceTimersByTimeAsync(0)
185β
186 expect(onMutate).toHaveBeenCalledTimes(1)
187 })
188β
189 test('should call onError when passed as an option', async () => {
190 const onError = vi.fn()
191 const mutation = TestBed.runInInjectionContext(() => {
192 return injectMutation(() => ({
193 mutationFn: (_params: string) =>
194 sleep(10).then(() => Promise.reject(new Error('Some error'))),
195 onError,
196 }))
197 })
198β
199 mutation.mutate('')
200β
201 await vi.advanceTimersByTimeAsync(11)
202β
203 expect(onError).toHaveBeenCalledTimes(1)
204 })
205β
206 test('should call onSuccess when passed as an option', async () => {
207 const onSuccess = vi.fn()
208 const mutation = TestBed.runInInjectionContext(() => {
209 return injectMutation(() => ({
210 mutationFn: (params: string) => sleep(10).then(() => params),
211 onSuccess,
212 }))
213 })
214β
215 mutation.mutate('')
216β
217 await vi.advanceTimersByTimeAsync(11)
218β
219 expect(onSuccess).toHaveBeenCalledTimes(1)
220 })
221β
222 test('should call onSettled when passed as an option', async () => {
223 const onSettled = vi.fn()
224 const mutation = TestBed.runInInjectionContext(() => {
225 return injectMutation(() => ({
226 mutationFn: (params: string) => sleep(10).then(() => params),
227 onSettled,
228 }))
229 })
230β
231 mutation.mutate('')
232β
233 await vi.advanceTimersByTimeAsync(11)
234β
235 expect(onSettled).toHaveBeenCalledTimes(1)
236 })
237β
238 test('should call onError when passed as an argument of mutate function', async () => {
239 const onError = vi.fn()
240 const mutation = TestBed.runInInjectionContext(() => {
241 return injectMutation(() => ({
242 mutationFn: (_params: string) =>
243 sleep(10).then(() => Promise.reject(new Error('Some error'))),
244 }))
245 })
246β
247 mutation.mutate('', { onError })
248β
249 await vi.advanceTimersByTimeAsync(11)
250β
251 expect(onError).toHaveBeenCalledTimes(1)
252 })
253β
254 test('should call onSuccess when passed as an argument of mutate function', async () => {
255 const onSuccess = vi.fn()
256 const mutation = TestBed.runInInjectionContext(() => {
257 return injectMutation(() => ({
258 mutationFn: (params: string) => sleep(10).then(() => params),
259 }))
260 })
261β
262 mutation.mutate('', { onSuccess })
263β
264 await vi.advanceTimersByTimeAsync(11)
265β
266 expect(onSuccess).toHaveBeenCalledTimes(1)
267 })
268β
269 test('should call onSettled when passed as an argument of mutate function', async () => {
270 const onSettled = vi.fn()
271 const mutation = TestBed.runInInjectionContext(() => {
272 return injectMutation(() => ({
273 mutationFn: (params: string) => sleep(10).then(() => params),
274 }))
275 })
276β
277 mutation.mutate('', { onSettled })
278β
279 await vi.advanceTimersByTimeAsync(11)
280β
281 expect(onSettled).toHaveBeenCalledTimes(1)
282 })
283β
284 test('should fire both onSettled functions', async () => {
285 const onSettled = vi.fn()
286 const onSettledOnFunction = vi.fn()
287 const mutation = TestBed.runInInjectionContext(() => {
288 return injectMutation(() => ({
289 mutationFn: (params: string) => sleep(10).then(() => params),
290 onSettled,
291 }))
292 })
293β
294 mutation.mutate('', { onSettled: onSettledOnFunction })
295β
296 await vi.advanceTimersByTimeAsync(11)
297β
298 expect(onSettled).toHaveBeenCalledTimes(1)
299 expect(onSettledOnFunction).toHaveBeenCalledTimes(1)
300 })
301 })
302β
303 test('should support required signal inputs', async () => {
304 const mutationCache = queryClient.getMutationCache()
305β
306 @Component({
307 selector: 'app-fake',
308 template: `
309 <button (click)="mutate()"></button>
310 <span>{{ mutation.data() }}</span>
311 `,
312 changeDetection: ChangeDetectionStrategy.OnPush,
313 })
314 class FakeComponent {
315 name = input.required<string>()
316β
317 mutation = injectMutation(() => ({
318 mutationKey: ['fake', this.name()],
319 mutationFn: () => sleep(10).then(() => this.name()),
320 }))
321β
322 mutate(): void {
323 this.mutation.mutate()
324 }
325 }
326β
327 registerSignalInput(FakeComponent, 'name')
328β
329 @Component({
330 template: `<app-fake [name]="name()" />`,
331 imports: [FakeComponent],
332 })
333 class HostComponent {
334 protected readonly name = signal('value')
335 }
336β
337 const fixture = TestBed.createComponent(HostComponent)
338 fixture.detectChanges()
339β
340 const hostButton = fixture.nativeElement.querySelector(
341 'button',
342 ) as HTMLButtonElement
343 hostButton.click()
344β
345 await vi.advanceTimersByTimeAsync(11)
346 fixture.detectChanges()
347β
348 const span = fixture.nativeElement.querySelector('span') as HTMLSpanElement
349 expect(span.textContent).toEqual('value')
350 const mutation = mutationCache.find({
351 mutationKey: ['fake', 'value'],
352 })
353 expect(mutation).toBeDefined()
354 expect(mutation!.options.mutationKey).toStrictEqual(['fake', 'value'])
355 })
356β
357 test('should update options on required signal input change', async () => {
358 const mutationCache = queryClient.getMutationCache()
359β
360 @Component({
361 selector: 'app-fake',
362 template: `
363 <button (click)="mutate()"></button>
364 <span>{{ mutation.data() }}</span>
365 `,
366 changeDetection: ChangeDetectionStrategy.OnPush,
367 })
368 class FakeComponent {
369 name = input.required<string>()
370β
371 mutation = injectMutation(() => ({
372 mutationKey: ['fake', this.name()],
373 mutationFn: () => sleep(10).then(() => this.name()),
374 }))
375β
376 mutate(): void {
377 this.mutation.mutate()
378 }
379 }
380β
381 registerSignalInput(FakeComponent, 'name')
382β
383 @Component({
384 template: `<app-fake [name]="name()" />`,
385 imports: [FakeComponent],
386 })
387 class HostComponent {
388 protected readonly name = signal('value')
389β
390 updateName(value: string): void {
391 this.name.set(value)
392 }
393 }
394β
395 const fixture = TestBed.createComponent(HostComponent)
396 fixture.detectChanges()
397β
398 let button = fixture.nativeElement.querySelector(
399 'button',
400 ) as HTMLButtonElement
401 button.click()
402 await vi.advanceTimersByTimeAsync(11)
403 fixture.detectChanges()
404β
405 let span = fixture.nativeElement.querySelector('span') as HTMLSpanElement
406 expect(span.textContent).toEqual('value')
407β
408 fixture.componentInstance.updateName('updatedValue')
409 fixture.detectChanges()
410β
411 button = fixture.nativeElement.querySelector('button') as HTMLButtonElement
412 button.click()
413 await vi.advanceTimersByTimeAsync(11)
414 fixture.detectChanges()
415β
416 span = fixture.nativeElement.querySelector('span') as HTMLSpanElement
417 expect(span.textContent).toEqual('updatedValue')
418β
419 const mutations = mutationCache.findAll()
420 expect(mutations.length).toBe(2)
421 const [mutation1, mutation2] = mutations
422 expect(mutation1!.options.mutationKey).toEqual(['fake', 'value'])
423 expect(mutation2!.options.mutationKey).toEqual(['fake', 'updatedValue'])
424 })
425β
426 describe('throwOnError', () => {
427 test('should evaluate throwOnError when mutation is expected to throw', async () => {
428 const err = new Error('Expected mock error. All is well!')
429 const boundaryFn = vi.fn()
430 const { mutate } = TestBed.runInInjectionContext(() => {
431 return injectMutation(() => ({
432 mutationKey: ['fake'],
433 mutationFn: () => {
434 return Promise.reject(err)
435 },
436 throwOnError: boundaryFn,
437 }))
438 })
439β
440 TestBed.tick()
441β
442 mutate()
443β
444 await vi.advanceTimersByTimeAsync(0)
445β
446 expect(boundaryFn).toHaveBeenCalledTimes(1)
447 expect(boundaryFn).toHaveBeenCalledWith(err)
448 })
449β
450 test('should emit zone error when throwOnError is true and mutate is used', async () => {
451 const err = new Error('Expected mock error. All is well!')
452 const zone = TestBed.inject(NgZone)
453 const zoneErrorEmitSpy = vi.spyOn(zone.onError, 'emit')
454 const runSpy = vi.spyOn(zone, 'run').mockImplementation((callback: any) => {
455 try {
456 return callback()
457 } catch {
458 return undefined
459 }
460 })
461β
462 const { mutate } = TestBed.runInInjectionContext(() =>
463 injectMutation(() => ({
464 mutationKey: ['fake'],
465 mutationFn: () => {
466 return sleep(0).then(() => Promise.reject(err))
467 },
468 throwOnError: true,
469 })),
470 )
471β
472 mutate()
473β
474 await vi.runAllTimersAsync()
475β
476 expect(zoneErrorEmitSpy).toHaveBeenCalledWith(err)
477 expect(runSpy).toHaveBeenCalled()
478 })
479 })
480β
481 test('should throw when throwOnError is true', async () => {
482 const err = new Error('Expected mock error. All is well!')
483 const { mutateAsync } = TestBed.runInInjectionContext(() => {
484 return injectMutation(() => ({
485 mutationKey: ['fake'],
486 mutationFn: () => {
487 return Promise.reject(err)
488 },
489 throwOnError: true,
490 }))
491 })
492β
493 await expect(() => mutateAsync()).rejects.toThrowError(err)
494 })
495β
496 test('should throw when throwOnError function returns true', async () => {
497 const err = new Error('Expected mock error. All is well!')
498 const { mutateAsync } = TestBed.runInInjectionContext(() => {
499 return injectMutation(() => ({
500 mutationKey: ['fake'],
501 mutationFn: () => {
502 return Promise.reject(err)
503 },
504 throwOnError: () => true,
505 }))
506 })
507β
508 await expect(() => mutateAsync()).rejects.toThrowError(err)
509 })
510β
511 describe('injection context', () => {
512 test('throws NG0203 with descriptive error outside injection context', () => {
513 expect(() => {
514 injectMutation(() => ({
515 mutationKey: ['injectionContextError'],
516 mutationFn: () => Promise.resolve(),
517 }))
518 }).toThrowError(/NG0203(.*?)injectMutation/)
519 })
520β
521 test('can be used outside injection context when passing an injector', () => {
522 expect(() => {
523 injectMutation(
524 () => ({
525 mutationKey: ['injectionContextError'],
526 mutationFn: () => Promise.resolve(),
527 }),
528 {
529 injector: TestBed.inject(Injector),
530 },
531 )
532 }).not.toThrow()
533 })
534β
535 test('should complete mutation before whenStable() resolves', async () => {
536 const app = TestBed.inject(ApplicationRef)
537 let mutationStarted = false
538 let mutationCompleted = false
539β
540 const mutation = TestBed.runInInjectionContext(() =>
541 injectMutation(() => ({
542 mutationKey: ['pendingTasksTest'],
543 mutationFn: async (data: string) => {
544 mutationStarted = true
545 await sleep(50)
546 mutationCompleted = true
547 return `processed: ${data}`
548 },
549 })),
550 )
551β
552 // Initial state
553 expect(mutation.data()).toBeUndefined()
554 expect(mutationStarted).toBe(false)
555β
556 // Start mutation
557 mutation.mutate('test')
558β
559 // Wait for mutation to start and Angular to be "stable"
560 const stablePromise = app.whenStable()
561 await vi.advanceTimersByTimeAsync(60)
562 await stablePromise
563β
564 // After whenStable(), mutation should be complete
565 expect(mutationStarted).toBe(true)
566 expect(mutationCompleted).toBe(true)
567 expect(mutation.isSuccess()).toBe(true)
568 expect(mutation.data()).toBe('processed: test')
569 })
570β
571 test('should handle synchronous mutation with retry', async () => {
572 TestBed.resetTestingModule()
573 TestBed.configureTestingModule({
574 providers: [
575 provideZonelessChangeDetection(),
576 provideTanStackQuery(queryClient),
577 ],
578 })
579β
580 const app = TestBed.inject(ApplicationRef)
581 let attemptCount = 0
582β
583 const mutation = TestBed.runInInjectionContext(() =>
584 injectMutation(() => ({
585 retry: 2,
586 retryDelay: 0, // No delay for synchronous retry
587 mutationFn: async (data: string) => {
588 attemptCount++
589 if (attemptCount <= 2) {
590 throw new Error(`Sync attempt ${attemptCount} failed`)
591 }
592 return `processed: ${data}`
593 },
594 })),
595 )
596β
597 // Start mutation
598 mutation.mutate('retry-test')
599β
600 // Synchronize pending effects for each retry attempt
601 TestBed.tick()
602 await Promise.resolve()
603 await vi.advanceTimersByTimeAsync(10)
604β
605 TestBed.tick()
606 await Promise.resolve()
607 await vi.advanceTimersByTimeAsync(10)
608β
609 TestBed.tick()
610β
611 const stablePromise = app.whenStable()
612 await Promise.resolve()
613 await vi.advanceTimersByTimeAsync(10)
614 await stablePromise
615β
616 expect(mutation.isSuccess()).toBe(true)
617 expect(mutation.data()).toBe('processed: retry-test')
618 expect(attemptCount).toBe(3) // Initial + 2 retries
619 })
620β
621 test('should handle multiple synchronous mutations on same key', async () => {
622 TestBed.resetTestingModule()
623 TestBed.configureTestingModule({
624 providers: [
625 provideZonelessChangeDetection(),
626 provideTanStackQuery(queryClient),
627 ],
628 })
629β
630 const app = TestBed.inject(ApplicationRef)
631 let callCount = 0
632β
633 const mutation1 = TestBed.runInInjectionContext(() =>
634 injectMutation(() => ({
635 mutationKey: ['sync-mutation-key'],
636 mutationFn: async (data: string) => {
637 callCount++
638 return `mutation1: ${data}`
639 },
640 })),
641 )
642β
643 const mutation2 = TestBed.runInInjectionContext(() =>
644 injectMutation(() => ({
645 mutationKey: ['sync-mutation-key'],
646 mutationFn: async (data: string) => {
647 callCount++
648 return `mutation2: ${data}`
649 },
650 })),
651 )
652β
653 // Start both mutations
654 mutation1.mutate('test1')
655 mutation2.mutate('test2')
656β
657 // Synchronize pending effects
658 TestBed.tick()
659β
660 const stablePromise = app.whenStable()
661 // Flush microtasks to allow TanStack Query's scheduled notifications to process
662 await Promise.resolve()
663 await vi.advanceTimersByTimeAsync(1)
664 await stablePromise
665β
666 expect(mutation1.isSuccess()).toBe(true)
667 expect(mutation1.data()).toBe('mutation1: test1')
668 expect(mutation2.isSuccess()).toBe(true)
669 expect(mutation2.data()).toBe('mutation2: test2')
670 expect(callCount).toBe(2)
671 })
672β
673 test('should handle synchronous mutation with optimistic updates', async () => {
674 TestBed.resetTestingModule()
675 TestBed.configureTestingModule({
676 providers: [
677 provideZonelessChangeDetection(),
678 provideTanStackQuery(queryClient),
679 ],
680 })
681β
682 const app = TestBed.inject(ApplicationRef)
683 const testQueryKey = ['sync-optimistic']
684 let onMutateCalled = false
685 let onSuccessCalled = false
686β
687 // Set initial data
688 queryClient.setQueryData(testQueryKey, 'initial')
689β
690 const mutation = TestBed.runInInjectionContext(() =>
691 injectMutation(() => ({
692 mutationFn: async (data: string) => {
693 await sleep(50)
694 return `final: ${data}`
695 },
696 onMutate: async (variables) => {
697 onMutateCalled = true
698 queryClient.setQueryData(testQueryKey, `optimistic: ${variables}`)
699 },
700 onSuccess: (data) => {
701 onSuccessCalled = true
702 queryClient.setQueryData(testQueryKey, data)
703 },
704 })),
705 )
706β
707 // Run effects
708 TestBed.tick()
709β
710 // Start mutation
711 expect(queryClient.getQueryData(testQueryKey)).toBe('initial')
712 mutation.mutate('test')
713β
714 // Flush microtasks to allow TanStack Query's scheduled notifications to process
715 await Promise.resolve()
716β
717 // Check for optimistic update in the same macro task
718 expect(onMutateCalled).toBe(true)
719 expect(queryClient.getQueryData(testQueryKey)).toBe('optimistic: test')
720β
721 // Check stability before the mutation completes, waiting for the next macro task
722 await vi.advanceTimersByTimeAsync(0)
723 expect(mutation.isPending()).toBe(true)
724 expect(await firstValueFrom(app.isStable)).toBe(false)
725β
726 // Wait for the mutation to complete
727 const stablePromise = app.whenStable()
728 await vi.advanceTimersByTimeAsync(60)
729 await stablePromise
730β
731 expect(onSuccessCalled).toBe(true)
732 expect(mutation.isSuccess()).toBe(true)
733 expect(mutation.data()).toBe('final: test')
734 expect(queryClient.getQueryData(testQueryKey)).toBe('final: test')
735 })
736β
737 test('should handle synchronous mutation cancellation', async () => {
738 TestBed.resetTestingModule()
739 TestBed.configureTestingModule({
740 providers: [
741 provideZonelessChangeDetection(),
742 provideTanStackQuery(queryClient),
743 ],
744 })
745β
746 const app = TestBed.inject(ApplicationRef)
747β
748 const mutation = TestBed.runInInjectionContext(() =>
749 injectMutation(() => ({
750 mutationKey: ['cancel-sync'],
751 mutationFn: async (data: string) => `processed: ${data}`, // Synchronous resolution
752 })),
753 )
754β
755 // Start mutation
756 mutation.mutate('test')
757β
758 // Synchronize pending effects
759 TestBed.tick()
760β
761 const stablePromise = app.whenStable()
762 // Flush microtasks to allow TanStack Query's scheduled notifications to process
763 await Promise.resolve()
764 await vi.advanceTimersByTimeAsync(1)
765 await stablePromise
766β
767 // Synchronous mutations complete immediately
768 expect(mutation.isSuccess()).toBe(true)
769 expect(mutation.data()).toBe('processed: test')
770 })
771 })
772})