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

inject-mutation.test.ts

763 lines21.5 KB

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})