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

inject-mutation.test.ts

728 lines20.4 KB

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