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