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