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

inject-mutation.test.ts

730 lines20.4 KB

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