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