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

inject-mutation.test.ts

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