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

inject-mutation.test.ts

724 lines21.2 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, it, vi } from 'vitest'
11import { By } from '@angular/platform-browser'
12import { render } from '@testing-library/angular'
13import { queryKey, sleep } from '@tanstack/query-test-utils'
14import { QueryClient, injectMutation, provideTanStackQuery } from '..'
15import { expectSignals, setFixtureSignalInputs } from './test-utils'
16​
17describe('injectMutation', () => {
18 let queryClient: QueryClient
19​
20 beforeEach(() => {
21 queryClient = new QueryClient()
22 vi.useFakeTimers()
23 TestBed.configureTestingModule({
24 providers: [
25 provideZonelessChangeDetection(),
26 provideTanStackQuery(queryClient),
27 ],
28 })
29 })
30​
31 afterEach(() => {
32 vi.useRealTimers()
33 })
34​
35 it('should be in idle state initially', () => {
36 const mutation = TestBed.runInInjectionContext(() => {
37 return injectMutation(() => ({
38 mutationFn: (params) => sleep(0).then(() => params),
39 }))
40 })
41​
42 expectSignals(mutation, {
43 isIdle: true,
44 isPending: false,
45 isError: false,
46 isSuccess: false,
47 })
48 })
49​
50 it('should change state after invoking mutate', async () => {
51 const result = 'Mock data'
52​
53 const mutation = TestBed.runInInjectionContext(() => {
54 return injectMutation(() => ({
55 mutationFn: (params: string) => sleep(10).then(() => params),
56 }))
57 })
58​
59 TestBed.tick()
60​
61 mutation.mutate(result)
62 await vi.advanceTimersByTimeAsync(0)
63​
64 expectSignals(mutation, {
65 isIdle: false,
66 isPending: true,
67 isError: false,
68 isSuccess: false,
69 data: undefined,
70 error: null,
71 })
72 })
73​
74 it('should return error when request fails', async () => {
75 const mutation = TestBed.runInInjectionContext(() => {
76 return injectMutation(() => ({
77 mutationFn: () =>
78 sleep(10).then(() => Promise.reject(new Error('Some error'))),
79 }))
80 })
81​
82 mutation.mutate()
83​
84 await vi.advanceTimersByTimeAsync(11)
85​
86 expectSignals(mutation, {
87 isIdle: false,
88 isPending: false,
89 isError: true,
90 isSuccess: false,
91 data: undefined,
92 error: Error('Some error'),
93 })
94 })
95​
96 it('should return data when request succeeds', async () => {
97 const result = 'Mock data'
98​
99 @Component({
100 template: `
101 <div>isIdle: {{ mutation.isIdle() }}</div>
102 <div>isPending: {{ mutation.isPending() }}</div>
103 <div>isError: {{ mutation.isError() }}</div>
104 <div>isSuccess: {{ mutation.isSuccess() }}</div>
105 <div>data: {{ mutation.data() ?? 'none' }}</div>
106 <div>error: {{ mutation.error()?.message ?? 'none' }}</div>
107 `,
108 })
109 class Page {
110 readonly mutation = injectMutation(() => ({
111 mutationFn: (params: string) => sleep(10).then(() => params),
112 }))
113 }
114​
115 const rendered = await render(Page)
116​
117 rendered.fixture.componentInstance.mutation.mutate(result)
118​
119 await vi.advanceTimersByTimeAsync(11)
120 rendered.fixture.detectChanges()
121​
122 expect(rendered.getByText('isIdle: false')).toBeInTheDocument()
123 expect(rendered.getByText('isPending: false')).toBeInTheDocument()
124 expect(rendered.getByText('isError: false')).toBeInTheDocument()
125 expect(rendered.getByText('isSuccess: true')).toBeInTheDocument()
126 expect(rendered.getByText(`data: ${result}`)).toBeInTheDocument()
127 expect(rendered.getByText('error: none')).toBeInTheDocument()
128 })
129​
130 it('should update mutation when reactive options change', () => {
131 const mutationCache = queryClient.getMutationCache()
132 // Signal will be updated before the mutation is called
133 // this test confirms that the mutation uses the updated value
134 const key1 = queryKey()
135 const key2 = queryKey()
136 const mutationKey = signal(key1)
137 const mutation = TestBed.runInInjectionContext(() => {
138 return injectMutation(() => ({
139 mutationKey: mutationKey(),
140 mutationFn: (params: string) => sleep(0).then(() => params),
141 }))
142 })
143​
144 mutationKey.set(key2)
145​
146 mutation.mutate('xyz')
147​
148 const mutations = mutationCache.find({ mutationKey: key2 })
149​
150 expect(mutations?.options.mutationKey).toEqual(key2)
151 })
152​
153 it('should reset state after invoking mutation.reset', async () => {
154 @Component({
155 template: `
156 <div>isIdle: {{ mutation.isIdle() }}</div>
157 <div>isPending: {{ mutation.isPending() }}</div>
158 <div>isError: {{ mutation.isError() }}</div>
159 <div>isSuccess: {{ mutation.isSuccess() }}</div>
160 <div>data: {{ mutation.data() ?? 'none' }}</div>
161 <div>error: {{ mutation.error()?.message ?? 'none' }}</div>
162 `,
163 })
164 class Page {
165 readonly mutation = injectMutation(() => ({
166 mutationFn: () =>
167 sleep(10).then(() => Promise.reject(new Error('Some error'))),
168 }))
169 }
170​
171 const rendered = await render(Page)
172​
173 rendered.fixture.componentInstance.mutation.mutate()
174​
175 await vi.advanceTimersByTimeAsync(11)
176 rendered.fixture.detectChanges()
177​
178 expect(rendered.getByText('isError: true')).toBeInTheDocument()
179 expect(rendered.getByText('error: Some error')).toBeInTheDocument()
180​
181 rendered.fixture.componentInstance.mutation.reset()
182​
183 await vi.advanceTimersByTimeAsync(0)
184 rendered.fixture.detectChanges()
185​
186 expect(rendered.getByText('isIdle: true')).toBeInTheDocument()
187 expect(rendered.getByText('isPending: false')).toBeInTheDocument()
188 expect(rendered.getByText('isError: false')).toBeInTheDocument()
189 expect(rendered.getByText('isSuccess: false')).toBeInTheDocument()
190 expect(rendered.getByText('data: none')).toBeInTheDocument()
191 expect(rendered.getByText('error: none')).toBeInTheDocument()
192 })
193​
194 describe('side effects', () => {
195 beforeEach(() => {
196 vi.clearAllMocks()
197 })
198​
199 it('should call onMutate when passed as an option', async () => {
200 const onMutate = vi.fn()
201 const mutation = TestBed.runInInjectionContext(() => {
202 return injectMutation(() => ({
203 mutationFn: (params: string) => sleep(10).then(() => params),
204 onMutate,
205 }))
206 })
207​
208 mutation.mutate('')
209​
210 await vi.advanceTimersByTimeAsync(0)
211​
212 expect(onMutate).toHaveBeenCalledTimes(1)
213 })
214​
215 it('should call onError when passed as an option', async () => {
216 const onError = vi.fn()
217 const mutation = TestBed.runInInjectionContext(() => {
218 return injectMutation(() => ({
219 mutationFn: (_params: string) =>
220 sleep(10).then(() => Promise.reject(new Error('Some error'))),
221 onError,
222 }))
223 })
224​
225 mutation.mutate('')
226​
227 await vi.advanceTimersByTimeAsync(11)
228​
229 expect(onError).toHaveBeenCalledTimes(1)
230 })
231​
232 it('should call onSuccess when passed as an option', async () => {
233 const onSuccess = vi.fn()
234 const mutation = TestBed.runInInjectionContext(() => {
235 return injectMutation(() => ({
236 mutationFn: (params: string) => sleep(10).then(() => params),
237 onSuccess,
238 }))
239 })
240​
241 mutation.mutate('')
242​
243 await vi.advanceTimersByTimeAsync(11)
244​
245 expect(onSuccess).toHaveBeenCalledTimes(1)
246 })
247​
248 it('should call onSettled when passed as an option', async () => {
249 const onSettled = vi.fn()
250 const mutation = TestBed.runInInjectionContext(() => {
251 return injectMutation(() => ({
252 mutationFn: (params: string) => sleep(10).then(() => params),
253 onSettled,
254 }))
255 })
256​
257 mutation.mutate('')
258​
259 await vi.advanceTimersByTimeAsync(11)
260​
261 expect(onSettled).toHaveBeenCalledTimes(1)
262 })
263​
264 it('should call onError when passed as an argument of mutate function', async () => {
265 const onError = vi.fn()
266 const mutation = TestBed.runInInjectionContext(() => {
267 return injectMutation(() => ({
268 mutationFn: (_params: string) =>
269 sleep(10).then(() => Promise.reject(new Error('Some error'))),
270 }))
271 })
272​
273 mutation.mutate('', { onError })
274​
275 await vi.advanceTimersByTimeAsync(11)
276​
277 expect(onError).toHaveBeenCalledTimes(1)
278 })
279​
280 it('should call onSuccess when passed as an argument of mutate function', async () => {
281 const onSuccess = vi.fn()
282 const mutation = TestBed.runInInjectionContext(() => {
283 return injectMutation(() => ({
284 mutationFn: (params: string) => sleep(10).then(() => params),
285 }))
286 })
287​
288 mutation.mutate('', { onSuccess })
289​
290 await vi.advanceTimersByTimeAsync(11)
291​
292 expect(onSuccess).toHaveBeenCalledTimes(1)
293 })
294​
295 it('should call onSettled when passed as an argument of mutate function', async () => {
296 const onSettled = vi.fn()
297 const mutation = TestBed.runInInjectionContext(() => {
298 return injectMutation(() => ({
299 mutationFn: (params: string) => sleep(10).then(() => params),
300 }))
301 })
302​
303 mutation.mutate('', { onSettled })
304​
305 await vi.advanceTimersByTimeAsync(11)
306​
307 expect(onSettled).toHaveBeenCalledTimes(1)
308 })
309​
310 it('should fire both onSettled functions', async () => {
311 const onSettled = vi.fn()
312 const onSettledOnFunction = vi.fn()
313 const mutation = TestBed.runInInjectionContext(() => {
314 return injectMutation(() => ({
315 mutationFn: (params: string) => sleep(10).then(() => params),
316 onSettled,
317 }))
318 })
319​
320 mutation.mutate('', { onSettled: onSettledOnFunction })
321​
322 await vi.advanceTimersByTimeAsync(11)
323​
324 expect(onSettled).toHaveBeenCalledTimes(1)
325 expect(onSettledOnFunction).toHaveBeenCalledTimes(1)
326 })
327 })
328​
329 it('should support required signal inputs', async () => {
330 const mutationCache = queryClient.getMutationCache()
331​
332 @Component({
333 selector: 'app-fake',
334 template: `
335 <button (click)="mutate()"></button>
336 <span>{{ mutation.data() }}</span>
337 `,
338 })
339 class FakeComponent {
340 name = input.required<string>()
341​
342 mutation = injectMutation(() => ({
343 mutationKey: ['fake', this.name()],
344 mutationFn: () => sleep(10).then(() => this.name()),
345 }))
346​
347 mutate(): void {
348 this.mutation.mutate()
349 }
350 }
351​
352 const fixture = TestBed.createComponent(FakeComponent)
353 const { debugElement } = fixture
354 setFixtureSignalInputs(fixture, { name: 'value' })
355​
356 const button = debugElement.query(By.css('button'))
357 button.triggerEventHandler('click')
358​
359 await vi.advanceTimersByTimeAsync(11)
360 fixture.detectChanges()
361​
362 const text = debugElement.query(By.css('span')).nativeElement.textContent
363 expect(text).toEqual('value')
364 const mutation = mutationCache.find({ mutationKey: ['fake', 'value'] })
365 expect(mutation).toBeDefined()
366 expect(mutation!.options.mutationKey).toStrictEqual(['fake', 'value'])
367 })
368​
369 it('should update options on required signal input change', async () => {
370 const mutationCache = queryClient.getMutationCache()
371​
372 @Component({
373 selector: 'app-fake',
374 template: `
375 <button (click)="mutate()"></button>
376 <span>{{ mutation.data() }}</span>
377 `,
378 })
379 class FakeComponent {
380 name = input.required<string>()
381​
382 mutation = injectMutation(() => ({
383 mutationKey: ['fake', this.name()],
384 mutationFn: () => sleep(10).then(() => this.name()),
385 }))
386​
387 mutate(): void {
388 this.mutation.mutate()
389 }
390 }
391​
392 const fixture = TestBed.createComponent(FakeComponent)
393 const { debugElement } = fixture
394 setFixtureSignalInputs(fixture, { name: 'value' })
395​
396 const button = debugElement.query(By.css('button'))
397 const span = debugElement.query(By.css('span'))
398​
399 button.triggerEventHandler('click')
400 await vi.advanceTimersByTimeAsync(11)
401 fixture.detectChanges()
402​
403 expect(span.nativeElement.textContent).toEqual('value')
404​
405 setFixtureSignalInputs(fixture, { name: 'updatedValue' })
406​
407 button.triggerEventHandler('click')
408 await vi.advanceTimersByTimeAsync(11)
409 fixture.detectChanges()
410​
411 expect(span.nativeElement.textContent).toEqual('updatedValue')
412​
413 const mutations = mutationCache.findAll()
414 expect(mutations.length).toBe(2)
415 const [mutation1, mutation2] = mutations
416 expect(mutation1!.options.mutationKey).toEqual(['fake', 'value'])
417 expect(mutation2!.options.mutationKey).toEqual(['fake', 'updatedValue'])
418 })
419​
420 describe('throwOnError', () => {
421 it('should evaluate throwOnError when mutation is expected to throw', async () => {
422 const key = queryKey()
423 const err = new Error('Expected mock error. All is well!')
424 const boundaryFn = vi.fn()
425 const { mutate } = TestBed.runInInjectionContext(() => {
426 return injectMutation(() => ({
427 mutationKey: key,
428 mutationFn: () => {
429 return Promise.reject(err)
430 },
431 throwOnError: boundaryFn,
432 }))
433 })
434​
435 TestBed.tick()
436​
437 mutate()
438​
439 await vi.advanceTimersByTimeAsync(0)
440​
441 expect(boundaryFn).toHaveBeenCalledTimes(1)
442 expect(boundaryFn).toHaveBeenCalledWith(err)
443 })
444​
445 it('should throw when throwOnError is true and mutate is used', async () => {
446 const key = queryKey()
447 const { mutate } = TestBed.runInInjectionContext(() => {
448 return injectMutation(() => ({
449 mutationKey: key,
450 mutationFn: () => {
451 return Promise.reject(
452 new Error('Expected mock error. All is well!'),
453 )
454 },
455 throwOnError: true,
456 }))
457 })
458​
459 TestBed.tick()
460​
461 mutate()
462​
463 await expect(vi.advanceTimersByTimeAsync(0)).rejects.toThrow(
464 'Expected mock error. All is well!',
465 )
466 })
467 })
468​
469 it('should throw when throwOnError is true', async () => {
470 const key = queryKey()
471 const err = new Error('Expected mock error. All is well!')
472 const { mutateAsync } = TestBed.runInInjectionContext(() => {
473 return injectMutation(() => ({
474 mutationKey: key,
475 mutationFn: () => {
476 return Promise.reject(err)
477 },
478 throwOnError: true,
479 }))
480 })
481​
482 await expect(() => mutateAsync()).rejects.toThrow(err)
483 })
484​
485 it('should throw when throwOnError function returns true', async () => {
486 const key = queryKey()
487 const err = new Error('Expected mock error. All is well!')
488 const { mutateAsync } = TestBed.runInInjectionContext(() => {
489 return injectMutation(() => ({
490 mutationKey: key,
491 mutationFn: () => {
492 return Promise.reject(err)
493 },
494 throwOnError: () => true,
495 }))
496 })
497​
498 await expect(() => mutateAsync()).rejects.toThrow(err)
499 })
500​
501 describe('injection context', () => {
502 it('should throw NG0203 with descriptive error outside injection context', () => {
503 const key = queryKey()
504 expect(() => {
505 injectMutation(() => ({
506 mutationKey: key,
507 mutationFn: () => Promise.resolve(),
508 }))
509 }).toThrow(/NG0203(.*?)injectMutation/)
510 })
511​
512 it('should be usable outside injection context when passing an injector', () => {
513 const key = queryKey()
514 expect(() => {
515 injectMutation(
516 () => ({
517 mutationKey: key,
518 mutationFn: () => Promise.resolve(),
519 }),
520 {
521 injector: TestBed.inject(Injector),
522 },
523 )
524 }).not.toThrow()
525 })
526​
527 it('should complete mutation before whenStable() resolves', async () => {
528 const app = TestBed.inject(ApplicationRef)
529 let mutationStarted = false
530 let mutationCompleted = false
531​
532 const key = queryKey()
533 const mutation = TestBed.runInInjectionContext(() =>
534 injectMutation(() => ({
535 mutationKey: key,
536 mutationFn: async (data: string) => {
537 mutationStarted = true
538 await sleep(50)
539 mutationCompleted = true
540 return `processed: ${data}`
541 },
542 })),
543 )
544​
545 // Initial state
546 expect(mutation.data()).toBeUndefined()
547 expect(mutationStarted).toBe(false)
548​
549 // Start mutation
550 mutation.mutate('test')
551​
552 // Wait for mutation to start and Angular to be "stable"
553 const stablePromise = app.whenStable()
554 await vi.advanceTimersByTimeAsync(60)
555 await stablePromise
556​
557 // After whenStable(), mutation should be complete
558 expect(mutationStarted).toBe(true)
559 expect(mutationCompleted).toBe(true)
560 expect(mutation.isSuccess()).toBe(true)
561 expect(mutation.data()).toBe('processed: test')
562 })
563​
564 it('should handle synchronous mutation with retry', async () => {
565 const app = TestBed.inject(ApplicationRef)
566 let attemptCount = 0
567​
568 const mutation = TestBed.runInInjectionContext(() =>
569 injectMutation(() => ({
570 retry: 2,
571 retryDelay: 0, // No delay for synchronous retry
572 mutationFn: async (data: string) => {
573 attemptCount++
574 if (attemptCount <= 2) {
575 throw new Error(`Sync attempt ${attemptCount} failed`)
576 }
577 return `processed: ${data}`
578 },
579 })),
580 )
581​
582 // Start mutation
583 mutation.mutate('retry-test')
584​
585 // Synchronize pending effects for each retry attempt
586 TestBed.tick()
587 await Promise.resolve()
588 await vi.advanceTimersByTimeAsync(10)
589​
590 TestBed.tick()
591 await Promise.resolve()
592 await vi.advanceTimersByTimeAsync(10)
593​
594 TestBed.tick()
595​
596 const stablePromise = app.whenStable()
597 await Promise.resolve()
598 await vi.advanceTimersByTimeAsync(10)
599 await stablePromise
600​
601 expect(mutation.isSuccess()).toBe(true)
602 expect(mutation.data()).toBe('processed: retry-test')
603 expect(attemptCount).toBe(3) // Initial + 2 retries
604 })
605​
606 it('should handle multiple synchronous mutations on same key', async () => {
607 const app = TestBed.inject(ApplicationRef)
608 let callCount = 0
609​
610 const key = queryKey()
611​
612 const mutation1 = TestBed.runInInjectionContext(() =>
613 injectMutation(() => ({
614 mutationKey: key,
615 mutationFn: async (data: string) => {
616 callCount++
617 return `mutation1: ${data}`
618 },
619 })),
620 )
621​
622 const mutation2 = TestBed.runInInjectionContext(() =>
623 injectMutation(() => ({
624 mutationKey: key,
625 mutationFn: async (data: string) => {
626 callCount++
627 return `mutation2: ${data}`
628 },
629 })),
630 )
631​
632 // Start both mutations
633 mutation1.mutate('test1')
634 mutation2.mutate('test2')
635​
636 // Synchronize pending effects
637 TestBed.tick()
638​
639 const stablePromise = app.whenStable()
640 // Flush microtasks to allow TanStack Query's scheduled notifications to process
641 await Promise.resolve()
642 await vi.advanceTimersByTimeAsync(1)
643 await stablePromise
644​
645 expect(mutation1.isSuccess()).toBe(true)
646 expect(mutation1.data()).toBe('mutation1: test1')
647 expect(mutation2.isSuccess()).toBe(true)
648 expect(mutation2.data()).toBe('mutation2: test2')
649 expect(callCount).toBe(2)
650 })
651​
652 it('should handle synchronous mutation with optimistic updates', async () => {
653 const app = TestBed.inject(ApplicationRef)
654 const testQueryKey = queryKey()
655 let onMutateCalled = false
656 let onSuccessCalled = false
657​
658 // Set initial data
659 queryClient.setQueryData(testQueryKey, 'initial')
660​
661 const mutation = TestBed.runInInjectionContext(() =>
662 injectMutation(() => ({
663 mutationFn: async (data: string) => `final: ${data}`, // Synchronous resolution
664 onMutate: async (variables) => {
665 onMutateCalled = true
666 const previousData = queryClient.getQueryData(testQueryKey)
667 queryClient.setQueryData(testQueryKey, `optimistic: ${variables}`)
668 return { previousData }
669 },
670 onSuccess: (data) => {
671 onSuccessCalled = true
672 queryClient.setQueryData(testQueryKey, data)
673 },
674 })),
675 )
676​
677 // Start mutation
678 mutation.mutate('test')
679​
680 // Synchronize pending effects
681 TestBed.tick()
682​
683 const stablePromise = app.whenStable()
684 // Flush microtasks to allow TanStack Query's scheduled notifications to process
685 await Promise.resolve()
686 await vi.advanceTimersByTimeAsync(1)
687 await stablePromise
688​
689 expect(onMutateCalled).toBe(true)
690 expect(onSuccessCalled).toBe(true)
691 expect(mutation.isSuccess()).toBe(true)
692 expect(mutation.data()).toBe('final: test')
693 expect(queryClient.getQueryData(testQueryKey)).toBe('final: test')
694 })
695​
696 it('should handle synchronous mutation cancellation', async () => {
697 const app = TestBed.inject(ApplicationRef)
698​
699 const key = queryKey()
700 const mutation = TestBed.runInInjectionContext(() =>
701 injectMutation(() => ({
702 mutationKey: key,
703 mutationFn: async (data: string) => `processed: ${data}`, // Synchronous resolution
704 })),
705 )
706​
707 // Start mutation
708 mutation.mutate('test')
709​
710 // Synchronize pending effects
711 TestBed.tick()
712​
713 const stablePromise = app.whenStable()
714 // Flush microtasks to allow TanStack Query's scheduled notifications to process
715 await Promise.resolve()
716 await vi.advanceTimersByTimeAsync(1)
717 await stablePromise
718​
719 // Synchronous mutations complete immediately
720 expect(mutation.isSuccess()).toBe(true)
721 expect(mutation.data()).toBe('processed: test')
722 })
723 })
724})