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

inject-mutation.test.ts

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