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