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, it, 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 it('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 it('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 it('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 it('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 it('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 it('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 it('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 it('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 it('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 it('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 it('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 it('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 it('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 it('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 it('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 detectChangesOnRender: false,
333 })
334 rendered.fixture.detectChanges()
335β
336 const fixture = rendered.fixture
337β
338 const hostButton = fixture.nativeElement.querySelector(
339 'button',
340 ) as HTMLButtonElement
341 hostButton.click()
342β
343 await vi.advanceTimersByTimeAsync(11)
344 fixture.detectChanges()
345β
346 const span = fixture.nativeElement.querySelector('span') as HTMLSpanElement
347 expect(span.textContent).toEqual('value')
348 const mutation = mutationCache.find({
349 mutationKey: ['fake', 'value'],
350 })
351 expect(mutation).toBeDefined()
352 expect(mutation!.options.mutationKey).toStrictEqual(['fake', 'value'])
353 })
354β
355 it('should update options on required signal input change', async () => {
356 const mutationCache = queryClient.getMutationCache()
357β
358 @Component({
359 selector: 'app-fake',
360 template: `
361 <button (click)="mutate()"></button>
362 <span>{{ mutation.data() }}</span>
363 `,
364 changeDetection: ChangeDetectionStrategy.OnPush,
365 })
366 class FakeComponent {
367 name = input.required<string>()
368β
369 mutation = injectMutation(() => ({
370 mutationKey: ['fake', this.name()],
371 mutationFn: () => sleep(10).then(() => this.name()),
372 }))
373β
374 mutate(): void {
375 this.mutation.mutate()
376 }
377β
378 }
379β
380 const name = signal('value')
381 const rendered = await render(FakeComponent, {
382 bindings: [inputBinding('name', name.asReadonly())],
383 detectChangesOnRender: false,
384 })
385 rendered.fixture.detectChanges()
386β
387 const fixture = rendered.fixture
388β
389 let button = fixture.nativeElement.querySelector(
390 'button',
391 ) as HTMLButtonElement
392 button.click()
393 await vi.advanceTimersByTimeAsync(11)
394 fixture.detectChanges()
395β
396 let span = fixture.nativeElement.querySelector('span') as HTMLSpanElement
397 expect(span.textContent).toEqual('value')
398β
399 name.set('updatedValue')
400 fixture.detectChanges()
401β
402 button = fixture.nativeElement.querySelector('button') as HTMLButtonElement
403 button.click()
404 await vi.advanceTimersByTimeAsync(11)
405 fixture.detectChanges()
406β
407 span = fixture.nativeElement.querySelector('span') as HTMLSpanElement
408 expect(span.textContent).toEqual('updatedValue')
409β
410 const mutations = mutationCache.findAll()
411 expect(mutations.length).toBe(2)
412 const [mutation1, mutation2] = mutations
413 expect(mutation1!.options.mutationKey).toEqual(['fake', 'value'])
414 expect(mutation2!.options.mutationKey).toEqual(['fake', 'updatedValue'])
415 })
416β
417 describe('throwOnError', () => {
418 it('should evaluate throwOnError when mutation is expected to throw', async () => {
419 const err = new Error('Expected mock error. All is well!')
420 const boundaryFn = vi.fn()
421 const { mutate } = TestBed.runInInjectionContext(() => {
422 return injectMutation(() => ({
423 mutationKey: ['fake'],
424 mutationFn: () => {
425 return Promise.reject(err)
426 },
427 throwOnError: boundaryFn,
428 }))
429 })
430β
431 TestBed.tick()
432β
433 mutate()
434β
435 await vi.advanceTimersByTimeAsync(0)
436β
437 expect(boundaryFn).toHaveBeenCalledTimes(1)
438 expect(boundaryFn).toHaveBeenCalledWith(err)
439 })
440β
441 it('should emit zone error when throwOnError is true and mutate is used', async () => {
442 const err = new Error('Expected mock error. All is well!')
443 const zone = TestBed.inject(NgZone)
444 const zoneErrorEmitSpy = vi.spyOn(zone.onError, 'emit')
445 const runSpy = vi.spyOn(zone, 'run').mockImplementation((callback: any) => {
446 try {
447 return callback()
448 } catch {
449 return undefined
450 }
451 })
452β
453 const { mutate } = TestBed.runInInjectionContext(() =>
454 injectMutation(() => ({
455 mutationKey: ['fake'],
456 mutationFn: () => {
457 return sleep(0).then(() => Promise.reject(err))
458 },
459 throwOnError: true,
460 })),
461 )
462β
463 mutate()
464β
465 await vi.runAllTimersAsync()
466β
467 expect(zoneErrorEmitSpy).toHaveBeenCalledWith(err)
468 expect(runSpy).toHaveBeenCalled()
469 })
470 })
471β
472 it('should throw when throwOnError is true', async () => {
473 const err = new Error('Expected mock error. All is well!')
474 const { mutateAsync } = TestBed.runInInjectionContext(() => {
475 return injectMutation(() => ({
476 mutationKey: ['fake'],
477 mutationFn: () => {
478 return Promise.reject(err)
479 },
480 throwOnError: true,
481 }))
482 })
483β
484 await expect(() => mutateAsync()).rejects.toThrowError(err)
485 })
486β
487 it('should throw when throwOnError function returns true', async () => {
488 const err = new Error('Expected mock error. All is well!')
489 const { mutateAsync } = TestBed.runInInjectionContext(() => {
490 return injectMutation(() => ({
491 mutationKey: ['fake'],
492 mutationFn: () => {
493 return Promise.reject(err)
494 },
495 throwOnError: () => true,
496 }))
497 })
498β
499 await expect(() => mutateAsync()).rejects.toThrowError(err)
500 })
501β
502 describe('injection context', () => {
503 it('throws NG0203 with descriptive error outside injection context', () => {
504 expect(() => {
505 injectMutation(() => ({
506 mutationKey: ['injectionContextError'],
507 mutationFn: () => Promise.resolve(),
508 }))
509 }).toThrowError(/NG0203(.*?)injectMutation/)
510 })
511β
512 it('can be used outside injection context when passing an injector', () => {
513 expect(() => {
514 injectMutation(
515 () => ({
516 mutationKey: ['injectionContextError'],
517 mutationFn: () => Promise.resolve(),
518 }),
519 {
520 injector: TestBed.inject(Injector),
521 },
522 )
523 }).not.toThrow()
524 })
525β
526 it('should complete mutation before whenStable() resolves', async () => {
527 const app = TestBed.inject(ApplicationRef)
528 let mutationStarted = false
529 let mutationCompleted = false
530β
531 const mutation = TestBed.runInInjectionContext(() =>
532 injectMutation(() => ({
533 mutationKey: ['pendingTasksTest'],
534 mutationFn: async (data: string) => {
535 mutationStarted = true
536 await sleep(50)
537 mutationCompleted = true
538 return `processed: ${data}`
539 },
540 })),
541 )
542β
543 // Initial state
544 expect(mutation.data()).toBeUndefined()
545 expect(mutationStarted).toBe(false)
546β
547 // Start mutation
548 mutation.mutate('test')
549β
550 // Wait for mutation to start and Angular to be "stable"
551 const stablePromise = app.whenStable()
552 await vi.advanceTimersByTimeAsync(60)
553 await stablePromise
554β
555 // After whenStable(), mutation should be complete
556 expect(mutationStarted).toBe(true)
557 expect(mutationCompleted).toBe(true)
558 expect(mutation.isSuccess()).toBe(true)
559 expect(mutation.data()).toBe('processed: test')
560 })
561β
562 it('should handle synchronous mutation with retry', async () => {
563 TestBed.resetTestingModule()
564 TestBed.configureTestingModule({
565 providers: [
566 provideZonelessChangeDetection(),
567 ...provideTanStackQuery(queryClient),
568 ],
569 })
570β
571 const app = TestBed.inject(ApplicationRef)
572 let attemptCount = 0
573β
574 const mutation = TestBed.runInInjectionContext(() =>
575 injectMutation(() => ({
576 retry: 2,
577 retryDelay: 0, // No delay for synchronous retry
578 mutationFn: async (data: string) => {
579 attemptCount++
580 if (attemptCount <= 2) {
581 throw new Error(`Sync attempt ${attemptCount} failed`)
582 }
583 return `processed: ${data}`
584 },
585 })),
586 )
587β
588 // Start mutation
589 mutation.mutate('retry-test')
590β
591 // Synchronize pending effects for each retry attempt
592 TestBed.tick()
593 await Promise.resolve()
594 await vi.advanceTimersByTimeAsync(10)
595β
596 TestBed.tick()
597 await Promise.resolve()
598 await vi.advanceTimersByTimeAsync(10)
599β
600 TestBed.tick()
601β
602 const stablePromise = app.whenStable()
603 await Promise.resolve()
604 await vi.advanceTimersByTimeAsync(10)
605 await stablePromise
606β
607 expect(mutation.isSuccess()).toBe(true)
608 expect(mutation.data()).toBe('processed: retry-test')
609 expect(attemptCount).toBe(3) // Initial + 2 retries
610 })
611β
612 it('should handle multiple synchronous mutations on same key', async () => {
613 TestBed.resetTestingModule()
614 TestBed.configureTestingModule({
615 providers: [
616 provideZonelessChangeDetection(),
617 ...provideTanStackQuery(queryClient),
618 ],
619 })
620β
621 const app = TestBed.inject(ApplicationRef)
622 let callCount = 0
623β
624 const mutation1 = TestBed.runInInjectionContext(() =>
625 injectMutation(() => ({
626 mutationKey: ['sync-mutation-key'],
627 mutationFn: async (data: string) => {
628 callCount++
629 return `mutation1: ${data}`
630 },
631 })),
632 )
633β
634 const mutation2 = TestBed.runInInjectionContext(() =>
635 injectMutation(() => ({
636 mutationKey: ['sync-mutation-key'],
637 mutationFn: async (data: string) => {
638 callCount++
639 return `mutation2: ${data}`
640 },
641 })),
642 )
643β
644 // Start both mutations
645 mutation1.mutate('test1')
646 mutation2.mutate('test2')
647β
648 // Synchronize pending effects
649 TestBed.tick()
650β
651 const stablePromise = app.whenStable()
652 // Flush microtasks to allow TanStack Query's scheduled notifications to process
653 await Promise.resolve()
654 await vi.advanceTimersByTimeAsync(1)
655 await stablePromise
656β
657 expect(mutation1.isSuccess()).toBe(true)
658 expect(mutation1.data()).toBe('mutation1: test1')
659 expect(mutation2.isSuccess()).toBe(true)
660 expect(mutation2.data()).toBe('mutation2: test2')
661 expect(callCount).toBe(2)
662 })
663β
664 it('should handle synchronous mutation with optimistic updates', async () => {
665 TestBed.resetTestingModule()
666 TestBed.configureTestingModule({
667 providers: [
668 provideZonelessChangeDetection(),
669 ...provideTanStackQuery(queryClient),
670 ],
671 })
672β
673 const app = TestBed.inject(ApplicationRef)
674 const testQueryKey = ['sync-optimistic']
675 let onMutateCalled = false
676 let onSuccessCalled = false
677β
678 // Set initial data
679 queryClient.setQueryData(testQueryKey, 'initial')
680β
681 const mutation = TestBed.runInInjectionContext(() =>
682 injectMutation(() => ({
683 mutationFn: async (data: string) => {
684 await sleep(50)
685 return `final: ${data}`
686 },
687 onMutate: async (variables) => {
688 onMutateCalled = true
689 queryClient.setQueryData(testQueryKey, `optimistic: ${variables}`)
690 },
691 onSuccess: (data) => {
692 onSuccessCalled = true
693 queryClient.setQueryData(testQueryKey, data)
694 },
695 })),
696 )
697β
698 // Run effects
699 TestBed.tick()
700β
701 // Start mutation
702 expect(queryClient.getQueryData(testQueryKey)).toBe('initial')
703 mutation.mutate('test')
704β
705 // Flush microtasks to allow TanStack Query's scheduled notifications to process
706 await Promise.resolve()
707β
708 // Check for optimistic update in the same macro task
709 expect(onMutateCalled).toBe(true)
710 expect(queryClient.getQueryData(testQueryKey)).toBe('optimistic: test')
711β
712 // Check stability before the mutation completes, waiting for the next macro task
713 await vi.advanceTimersByTimeAsync(0)
714 expect(mutation.isPending()).toBe(true)
715 expect(await firstValueFrom(app.isStable)).toBe(false)
716β
717 // Wait for the mutation to complete
718 const stablePromise = app.whenStable()
719 await vi.advanceTimersByTimeAsync(60)
720 await stablePromise
721β
722 expect(onSuccessCalled).toBe(true)
723 expect(mutation.isSuccess()).toBe(true)
724 expect(mutation.data()).toBe('final: test')
725 expect(queryClient.getQueryData(testQueryKey)).toBe('final: test')
726 })
727β
728 it('should handle synchronous mutation cancellation', async () => {
729 TestBed.resetTestingModule()
730 TestBed.configureTestingModule({
731 providers: [
732 provideZonelessChangeDetection(),
733 ...provideTanStackQuery(queryClient),
734 ],
735 })
736β
737 const app = TestBed.inject(ApplicationRef)
738β
739 const mutation = TestBed.runInInjectionContext(() =>
740 injectMutation(() => ({
741 mutationKey: ['cancel-sync'],
742 mutationFn: async (data: string) => `processed: ${data}`, // Synchronous resolution
743 })),
744 )
745β
746 // Start mutation
747 mutation.mutate('test')
748β
749 // Synchronize pending effects
750 TestBed.tick()
751β
752 const stablePromise = app.whenStable()
753 // Flush microtasks to allow TanStack Query's scheduled notifications to process
754 await Promise.resolve()
755 await vi.advanceTimersByTimeAsync(1)
756 await stablePromise
757β
758 // Synchronous mutations complete immediately
759 expect(mutation.isSuccess()).toBe(true)
760 expect(mutation.data()).toBe('processed: test')
761 })
762 })
763})