Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

inject-mutation.test.ts

772 lines21.7 KB

1import {
2 ApplicationRef,
3 ChangeDetectionStrategy,
4 Component,
5 Injector,
6 NgZone,
7 input,
8 provideZonelessChangeDetection,
9 signal,
10} from '@angular/core'
11import { TestBed } from '@angular/core/testing'
12import { sleep } from '@tanstack/query-test-utils'
13import { firstValueFrom } from 'rxjs'
14import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
15import { QueryClient, injectMutation, provideTanStackQuery } from '..'
16import { expectSignals, registerSignalInput } from './test-utils'
17​
18describe('injectMutation', () => {
19 let queryClient: QueryClient
20​
21 beforeEach(() => {
22 queryClient = new QueryClient()
23 vi.useFakeTimers()
24 TestBed.configureTestingModule({
25 providers: [
26 provideZonelessChangeDetection(),
27 provideTanStackQuery(queryClient),
28 ],
29 })
30 })
31​
32 afterEach(() => {
33 vi.useRealTimers()
34 })
35​
36 test('should be in idle state initially', () => {
37 const mutation = TestBed.runInInjectionContext(() => {
38 return injectMutation(() => ({
39 mutationFn: (params) => sleep(0).then(() => params),
40 }))
41 })
42​
43 expectSignals(mutation, {
44 isIdle: true,
45 isPending: false,
46 isError: false,
47 isSuccess: false,
48 })
49 })
50​
51 test('should change state after invoking mutate', async () => {
52 const result = 'Mock data'
53​
54 const mutation = TestBed.runInInjectionContext(() => {
55 return injectMutation(() => ({
56 mutationFn: (params: string) => sleep(10).then(() => params),
57 }))
58 })
59​
60 TestBed.tick()
61​
62 mutation.mutate(result)
63 await vi.advanceTimersByTimeAsync(0)
64​
65 expectSignals(mutation, {
66 isIdle: false,
67 isPending: true,
68 isError: false,
69 isSuccess: false,
70 data: undefined,
71 error: null,
72 })
73 })
74​
75 test('should return error when request fails', async () => {
76 const mutation = TestBed.runInInjectionContext(() => {
77 return injectMutation(() => ({
78 mutationFn: () =>
79 sleep(10).then(() => Promise.reject(new Error('Some error'))),
80 }))
81 })
82​
83 mutation.mutate()
84​
85 await vi.advanceTimersByTimeAsync(11)
86​
87 expectSignals(mutation, {
88 isIdle: false,
89 isPending: false,
90 isError: true,
91 isSuccess: false,
92 data: undefined,
93 error: Error('Some error'),
94 })
95 })
96​
97 test('should return data when request succeeds', async () => {
98 const result = 'Mock data'
99 const mutation = TestBed.runInInjectionContext(() => {
100 return injectMutation(() => ({
101 mutationFn: (params: string) => sleep(10).then(() => params),
102 }))
103 })
104​
105 mutation.mutate(result)
106​
107 await vi.advanceTimersByTimeAsync(11)
108​
109 expectSignals(mutation, {
110 isIdle: false,
111 isPending: false,
112 isError: false,
113 isSuccess: true,
114 data: result,
115 error: null,
116 })
117 })
118​
119 test('reactive options should update mutation', () => {
120 const mutationCache = queryClient.getMutationCache()
121 // Signal will be updated before the mutation is called
122 // this test confirms that the mutation uses the updated value
123 const mutationKey = signal(['1'])
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(['2'])
132​
133 mutation.mutate('xyz')
134​
135 const mutations = mutationCache.find({ mutationKey: ['2'] })
136​
137 expect(mutations?.options.mutationKey).toEqual(['2'])
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 changeDetection: ChangeDetectionStrategy.OnPush,
313 })
314 class FakeComponent {
315 name = input.required<string>()
316​
317 mutation = injectMutation(() => ({
318 mutationKey: ['fake', this.name()],
319 mutationFn: () => sleep(10).then(() => this.name()),
320 }))
321​
322 mutate(): void {
323 this.mutation.mutate()
324 }
325 }
326​
327 registerSignalInput(FakeComponent, 'name')
328​
329 @Component({
330 template: `<app-fake [name]="name()" />`,
331 imports: [FakeComponent],
332 })
333 class HostComponent {
334 protected readonly name = signal('value')
335 }
336​
337 const fixture = TestBed.createComponent(HostComponent)
338 fixture.detectChanges()
339​
340 const hostButton = fixture.nativeElement.querySelector(
341 'button',
342 ) as HTMLButtonElement
343 hostButton.click()
344​
345 await vi.advanceTimersByTimeAsync(11)
346 fixture.detectChanges()
347​
348 const span = fixture.nativeElement.querySelector('span') as HTMLSpanElement
349 expect(span.textContent).toEqual('value')
350 const mutation = mutationCache.find({
351 mutationKey: ['fake', 'value'],
352 })
353 expect(mutation).toBeDefined()
354 expect(mutation!.options.mutationKey).toStrictEqual(['fake', 'value'])
355 })
356​
357 test('should update options on required signal input change', async () => {
358 const mutationCache = queryClient.getMutationCache()
359​
360 @Component({
361 selector: 'app-fake',
362 template: `
363 <button (click)="mutate()"></button>
364 <span>{{ mutation.data() }}</span>
365 `,
366 changeDetection: ChangeDetectionStrategy.OnPush,
367 })
368 class FakeComponent {
369 name = input.required<string>()
370​
371 mutation = injectMutation(() => ({
372 mutationKey: ['fake', this.name()],
373 mutationFn: () => sleep(10).then(() => this.name()),
374 }))
375​
376 mutate(): void {
377 this.mutation.mutate()
378 }
379 }
380​
381 registerSignalInput(FakeComponent, 'name')
382​
383 @Component({
384 template: `<app-fake [name]="name()" />`,
385 imports: [FakeComponent],
386 })
387 class HostComponent {
388 protected readonly name = signal('value')
389​
390 updateName(value: string): void {
391 this.name.set(value)
392 }
393 }
394​
395 const fixture = TestBed.createComponent(HostComponent)
396 fixture.detectChanges()
397​
398 let button = fixture.nativeElement.querySelector(
399 'button',
400 ) as HTMLButtonElement
401 button.click()
402 await vi.advanceTimersByTimeAsync(11)
403 fixture.detectChanges()
404​
405 let span = fixture.nativeElement.querySelector('span') as HTMLSpanElement
406 expect(span.textContent).toEqual('value')
407​
408 fixture.componentInstance.updateName('updatedValue')
409 fixture.detectChanges()
410​
411 button = fixture.nativeElement.querySelector('button') as HTMLButtonElement
412 button.click()
413 await vi.advanceTimersByTimeAsync(11)
414 fixture.detectChanges()
415​
416 span = fixture.nativeElement.querySelector('span') as HTMLSpanElement
417 expect(span.textContent).toEqual('updatedValue')
418​
419 const mutations = mutationCache.findAll()
420 expect(mutations.length).toBe(2)
421 const [mutation1, mutation2] = mutations
422 expect(mutation1!.options.mutationKey).toEqual(['fake', 'value'])
423 expect(mutation2!.options.mutationKey).toEqual(['fake', 'updatedValue'])
424 })
425​
426 describe('throwOnError', () => {
427 test('should evaluate throwOnError when mutation is expected to throw', async () => {
428 const err = new Error('Expected mock error. All is well!')
429 const boundaryFn = vi.fn()
430 const { mutate } = TestBed.runInInjectionContext(() => {
431 return injectMutation(() => ({
432 mutationKey: ['fake'],
433 mutationFn: () => {
434 return Promise.reject(err)
435 },
436 throwOnError: boundaryFn,
437 }))
438 })
439​
440 TestBed.tick()
441​
442 mutate()
443​
444 await vi.advanceTimersByTimeAsync(0)
445​
446 expect(boundaryFn).toHaveBeenCalledTimes(1)
447 expect(boundaryFn).toHaveBeenCalledWith(err)
448 })
449​
450 test('should emit zone error when throwOnError is true and mutate is used', async () => {
451 const err = new Error('Expected mock error. All is well!')
452 const zone = TestBed.inject(NgZone)
453 const zoneErrorEmitSpy = vi.spyOn(zone.onError, 'emit')
454 const runSpy = vi.spyOn(zone, 'run').mockImplementation((callback: any) => {
455 try {
456 return callback()
457 } catch {
458 return undefined
459 }
460 })
461​
462 const { mutate } = TestBed.runInInjectionContext(() =>
463 injectMutation(() => ({
464 mutationKey: ['fake'],
465 mutationFn: () => {
466 return sleep(0).then(() => Promise.reject(err))
467 },
468 throwOnError: true,
469 })),
470 )
471​
472 mutate()
473​
474 await vi.runAllTimersAsync()
475​
476 expect(zoneErrorEmitSpy).toHaveBeenCalledWith(err)
477 expect(runSpy).toHaveBeenCalled()
478 })
479 })
480​
481 test('should throw when throwOnError is true', async () => {
482 const err = new Error('Expected mock error. All is well!')
483 const { mutateAsync } = TestBed.runInInjectionContext(() => {
484 return injectMutation(() => ({
485 mutationKey: ['fake'],
486 mutationFn: () => {
487 return Promise.reject(err)
488 },
489 throwOnError: true,
490 }))
491 })
492​
493 await expect(() => mutateAsync()).rejects.toThrowError(err)
494 })
495​
496 test('should throw when throwOnError function returns true', async () => {
497 const err = new Error('Expected mock error. All is well!')
498 const { mutateAsync } = TestBed.runInInjectionContext(() => {
499 return injectMutation(() => ({
500 mutationKey: ['fake'],
501 mutationFn: () => {
502 return Promise.reject(err)
503 },
504 throwOnError: () => true,
505 }))
506 })
507​
508 await expect(() => mutateAsync()).rejects.toThrowError(err)
509 })
510​
511 describe('injection context', () => {
512 test('throws NG0203 with descriptive error outside injection context', () => {
513 expect(() => {
514 injectMutation(() => ({
515 mutationKey: ['injectionContextError'],
516 mutationFn: () => Promise.resolve(),
517 }))
518 }).toThrowError(/NG0203(.*?)injectMutation/)
519 })
520​
521 test('can be used outside injection context when passing an injector', () => {
522 expect(() => {
523 injectMutation(
524 () => ({
525 mutationKey: ['injectionContextError'],
526 mutationFn: () => Promise.resolve(),
527 }),
528 {
529 injector: TestBed.inject(Injector),
530 },
531 )
532 }).not.toThrow()
533 })
534​
535 test('should complete mutation before whenStable() resolves', async () => {
536 const app = TestBed.inject(ApplicationRef)
537 let mutationStarted = false
538 let mutationCompleted = false
539​
540 const mutation = TestBed.runInInjectionContext(() =>
541 injectMutation(() => ({
542 mutationKey: ['pendingTasksTest'],
543 mutationFn: async (data: string) => {
544 mutationStarted = true
545 await sleep(50)
546 mutationCompleted = true
547 return `processed: ${data}`
548 },
549 })),
550 )
551​
552 // Initial state
553 expect(mutation.data()).toBeUndefined()
554 expect(mutationStarted).toBe(false)
555​
556 // Start mutation
557 mutation.mutate('test')
558​
559 // Wait for mutation to start and Angular to be "stable"
560 const stablePromise = app.whenStable()
561 await vi.advanceTimersByTimeAsync(60)
562 await stablePromise
563​
564 // After whenStable(), mutation should be complete
565 expect(mutationStarted).toBe(true)
566 expect(mutationCompleted).toBe(true)
567 expect(mutation.isSuccess()).toBe(true)
568 expect(mutation.data()).toBe('processed: test')
569 })
570​
571 test('should handle synchronous mutation with retry', async () => {
572 TestBed.resetTestingModule()
573 TestBed.configureTestingModule({
574 providers: [
575 provideZonelessChangeDetection(),
576 provideTanStackQuery(queryClient),
577 ],
578 })
579​
580 const app = TestBed.inject(ApplicationRef)
581 let attemptCount = 0
582​
583 const mutation = TestBed.runInInjectionContext(() =>
584 injectMutation(() => ({
585 retry: 2,
586 retryDelay: 0, // No delay for synchronous retry
587 mutationFn: async (data: string) => {
588 attemptCount++
589 if (attemptCount <= 2) {
590 throw new Error(`Sync attempt ${attemptCount} failed`)
591 }
592 return `processed: ${data}`
593 },
594 })),
595 )
596​
597 // Start mutation
598 mutation.mutate('retry-test')
599​
600 // Synchronize pending effects for each retry attempt
601 TestBed.tick()
602 await Promise.resolve()
603 await vi.advanceTimersByTimeAsync(10)
604​
605 TestBed.tick()
606 await Promise.resolve()
607 await vi.advanceTimersByTimeAsync(10)
608​
609 TestBed.tick()
610​
611 const stablePromise = app.whenStable()
612 await Promise.resolve()
613 await vi.advanceTimersByTimeAsync(10)
614 await stablePromise
615​
616 expect(mutation.isSuccess()).toBe(true)
617 expect(mutation.data()).toBe('processed: retry-test')
618 expect(attemptCount).toBe(3) // Initial + 2 retries
619 })
620​
621 test('should handle multiple synchronous mutations on same key', async () => {
622 TestBed.resetTestingModule()
623 TestBed.configureTestingModule({
624 providers: [
625 provideZonelessChangeDetection(),
626 provideTanStackQuery(queryClient),
627 ],
628 })
629​
630 const app = TestBed.inject(ApplicationRef)
631 let callCount = 0
632​
633 const mutation1 = TestBed.runInInjectionContext(() =>
634 injectMutation(() => ({
635 mutationKey: ['sync-mutation-key'],
636 mutationFn: async (data: string) => {
637 callCount++
638 return `mutation1: ${data}`
639 },
640 })),
641 )
642​
643 const mutation2 = TestBed.runInInjectionContext(() =>
644 injectMutation(() => ({
645 mutationKey: ['sync-mutation-key'],
646 mutationFn: async (data: string) => {
647 callCount++
648 return `mutation2: ${data}`
649 },
650 })),
651 )
652​
653 // Start both mutations
654 mutation1.mutate('test1')
655 mutation2.mutate('test2')
656​
657 // Synchronize pending effects
658 TestBed.tick()
659​
660 const stablePromise = app.whenStable()
661 // Flush microtasks to allow TanStack Query's scheduled notifications to process
662 await Promise.resolve()
663 await vi.advanceTimersByTimeAsync(1)
664 await stablePromise
665​
666 expect(mutation1.isSuccess()).toBe(true)
667 expect(mutation1.data()).toBe('mutation1: test1')
668 expect(mutation2.isSuccess()).toBe(true)
669 expect(mutation2.data()).toBe('mutation2: test2')
670 expect(callCount).toBe(2)
671 })
672​
673 test('should handle synchronous mutation with optimistic updates', async () => {
674 TestBed.resetTestingModule()
675 TestBed.configureTestingModule({
676 providers: [
677 provideZonelessChangeDetection(),
678 provideTanStackQuery(queryClient),
679 ],
680 })
681​
682 const app = TestBed.inject(ApplicationRef)
683 const testQueryKey = ['sync-optimistic']
684 let onMutateCalled = false
685 let onSuccessCalled = false
686​
687 // Set initial data
688 queryClient.setQueryData(testQueryKey, 'initial')
689​
690 const mutation = TestBed.runInInjectionContext(() =>
691 injectMutation(() => ({
692 mutationFn: async (data: string) => {
693 await sleep(50)
694 return `final: ${data}`
695 },
696 onMutate: async (variables) => {
697 onMutateCalled = true
698 queryClient.setQueryData(testQueryKey, `optimistic: ${variables}`)
699 },
700 onSuccess: (data) => {
701 onSuccessCalled = true
702 queryClient.setQueryData(testQueryKey, data)
703 },
704 })),
705 )
706​
707 // Run effects
708 TestBed.tick()
709​
710 // Start mutation
711 expect(queryClient.getQueryData(testQueryKey)).toBe('initial')
712 mutation.mutate('test')
713​
714 // Flush microtasks to allow TanStack Query's scheduled notifications to process
715 await Promise.resolve()
716​
717 // Check for optimistic update in the same macro task
718 expect(onMutateCalled).toBe(true)
719 expect(queryClient.getQueryData(testQueryKey)).toBe('optimistic: test')
720​
721 // Check stability before the mutation completes, waiting for the next macro task
722 await vi.advanceTimersByTimeAsync(0)
723 expect(mutation.isPending()).toBe(true)
724 expect(await firstValueFrom(app.isStable)).toBe(false)
725​
726 // Wait for the mutation to complete
727 const stablePromise = app.whenStable()
728 await vi.advanceTimersByTimeAsync(60)
729 await stablePromise
730​
731 expect(onSuccessCalled).toBe(true)
732 expect(mutation.isSuccess()).toBe(true)
733 expect(mutation.data()).toBe('final: test')
734 expect(queryClient.getQueryData(testQueryKey)).toBe('final: test')
735 })
736​
737 test('should handle synchronous mutation cancellation', async () => {
738 TestBed.resetTestingModule()
739 TestBed.configureTestingModule({
740 providers: [
741 provideZonelessChangeDetection(),
742 provideTanStackQuery(queryClient),
743 ],
744 })
745​
746 const app = TestBed.inject(ApplicationRef)
747​
748 const mutation = TestBed.runInInjectionContext(() =>
749 injectMutation(() => ({
750 mutationKey: ['cancel-sync'],
751 mutationFn: async (data: string) => `processed: ${data}`, // Synchronous resolution
752 })),
753 )
754​
755 // Start mutation
756 mutation.mutate('test')
757​
758 // Synchronize pending effects
759 TestBed.tick()
760​
761 const stablePromise = app.whenStable()
762 // Flush microtasks to allow TanStack Query's scheduled notifications to process
763 await Promise.resolve()
764 await vi.advanceTimersByTimeAsync(1)
765 await stablePromise
766​
767 // Synchronous mutations complete immediately
768 expect(mutation.isSuccess()).toBe(true)
769 expect(mutation.data()).toBe('processed: test')
770 })
771 })
772})