Open History to see the last commit
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 { createKey, sleep } from '@tanstack/query-test-utils'
14import { noop } from '@tanstack/query-core'
15import { QueryClient, injectMutation, provideTanStackQuery } from '..'
16import { expectSignals, setFixtureSignalInputs } from './test-utils'
17import type { MutationFunctionContext } from '@tanstack/query-core'
18β
19describe('injectMutation', () => {
20 let queryClient: QueryClient
21β
22 beforeEach(() => {
23 queryClient = new QueryClient()
24 vi.useFakeTimers()
25 TestBed.configureTestingModule({
26 providers: [
27 provideZonelessChangeDetection(),
28 provideTanStackQuery(queryClient),
29 ],
30 })
31 })
32β
33 afterEach(() => {
34 vi.useRealTimers()
35 })
36β
37 it('should be in idle state initially', () => {
38 const mutation = TestBed.runInInjectionContext(() => {
39 return injectMutation(() => ({
40 mutationFn: (params) => sleep(0).then(() => params),
41 }))
42 })
43β
44 expectSignals(mutation, {
45 isIdle: true,
46 isPending: false,
47 isError: false,
48 isSuccess: false,
49 })
50 })
51β
52 it('should change state after invoking mutate', async () => {
53 const result = 'Mock data'
54β
55 @Component({
56 template: `
57 <div>isIdle: {{ mutation.isIdle() }}</div>
58 <div>isPending: {{ mutation.isPending() }}</div>
59 <div>isError: {{ mutation.isError() }}</div>
60 <div>isSuccess: {{ mutation.isSuccess() }}</div>
61 <div>data: {{ mutation.data() ?? 'none' }}</div>
62 <div>error: {{ mutation.error()?.message ?? 'none' }}</div>
63 `,
64 })
65 class Page {
66 readonly mutation = injectMutation(() => ({
67 mutationFn: (params: string) => sleep(10).then(() => params),
68 }))
69 }
70β
71 const rendered = await render(Page)
72β
73 rendered.fixture.componentInstance.mutation.mutate(result)
74 await vi.advanceTimersByTimeAsync(0)
75 rendered.fixture.detectChanges()
76 expect(rendered.getByText('isIdle: false')).toBeInTheDocument()
77 expect(rendered.getByText('isPending: true')).toBeInTheDocument()
78 expect(rendered.getByText('isError: false')).toBeInTheDocument()
79 expect(rendered.getByText('isSuccess: false')).toBeInTheDocument()
80 expect(rendered.getByText('data: none')).toBeInTheDocument()
81 expect(rendered.getByText('error: none')).toBeInTheDocument()
82 })
83β
84 it('should return error when request fails', async () => {
85 @Component({
86 template: `
87 <div>isIdle: {{ mutation.isIdle() }}</div>
88 <div>isPending: {{ mutation.isPending() }}</div>
89 <div>isError: {{ mutation.isError() }}</div>
90 <div>isSuccess: {{ mutation.isSuccess() }}</div>
91 <div>data: {{ mutation.data() ?? 'none' }}</div>
92 <div>error: {{ mutation.error()?.message ?? 'none' }}</div>
93 `,
94 })
95 class Page {
96 readonly mutation = injectMutation(() => ({
97 mutationFn: () =>
98 sleep(10).then(() => Promise.reject(new Error('Some error'))),
99 }))
100 }
101β
102 const rendered = await render(Page)
103β
104 rendered.fixture.componentInstance.mutation.mutate()
105 await vi.advanceTimersByTimeAsync(11)
106 rendered.fixture.detectChanges()
107 expect(rendered.getByText('isIdle: false')).toBeInTheDocument()
108 expect(rendered.getByText('isPending: false')).toBeInTheDocument()
109 expect(rendered.getByText('isError: true')).toBeInTheDocument()
110 expect(rendered.getByText('isSuccess: false')).toBeInTheDocument()
111 expect(rendered.getByText('data: none')).toBeInTheDocument()
112 expect(rendered.getByText('error: Some error')).toBeInTheDocument()
113 })
114β
115 it('should return data when request succeeds', async () => {
116 const result = 'Mock data'
117β
118 @Component({
119 template: `
120 <div>isIdle: {{ mutation.isIdle() }}</div>
121 <div>isPending: {{ mutation.isPending() }}</div>
122 <div>isError: {{ mutation.isError() }}</div>
123 <div>isSuccess: {{ mutation.isSuccess() }}</div>
124 <div>data: {{ mutation.data() ?? 'none' }}</div>
125 <div>error: {{ mutation.error()?.message ?? 'none' }}</div>
126 `,
127 })
128 class Page {
129 readonly mutation = injectMutation(() => ({
130 mutationFn: (params: string) => sleep(10).then(() => params),
131 }))
132 }
133β
134 const rendered = await render(Page)
135β
136 rendered.fixture.componentInstance.mutation.mutate(result)
137 await vi.advanceTimersByTimeAsync(11)
138 rendered.fixture.detectChanges()
139 expect(rendered.getByText('isIdle: false')).toBeInTheDocument()
140 expect(rendered.getByText('isPending: false')).toBeInTheDocument()
141 expect(rendered.getByText('isError: false')).toBeInTheDocument()
142 expect(rendered.getByText('isSuccess: true')).toBeInTheDocument()
143 expect(rendered.getByText(`data: ${result}`)).toBeInTheDocument()
144 expect(rendered.getByText('error: none')).toBeInTheDocument()
145 })
146β
147 it('should update mutation when reactive options change', () => {
148 const mutationCache = queryClient.getMutationCache()
149 // Signal will be updated before the mutation is called
150 // this test confirms that the mutation uses the updated value
151 const key1 = createKey()
152 const key2 = createKey()
153 const mutationKey = signal(key1)
154 const mutation = TestBed.runInInjectionContext(() => {
155 return injectMutation(() => ({
156 mutationKey: mutationKey(),
157 mutationFn: (params: string) => sleep(0).then(() => params),
158 }))
159 })
160β
161 mutationKey.set(key2)
162β
163 mutation.mutate('xyz')
164β
165 const mutations = mutationCache.find({ mutationKey: key2 })
166β
167 expect(mutations?.options.mutationKey).toStrictEqual(key2)
168 })
169β
170 it('should reset state after invoking mutation.reset', async () => {
171 @Component({
172 template: `
173 <div>isIdle: {{ mutation.isIdle() }}</div>
174 <div>isPending: {{ mutation.isPending() }}</div>
175 <div>isError: {{ mutation.isError() }}</div>
176 <div>isSuccess: {{ mutation.isSuccess() }}</div>
177 <div>data: {{ mutation.data() ?? 'none' }}</div>
178 <div>error: {{ mutation.error()?.message ?? 'none' }}</div>
179 `,
180 })
181 class Page {
182 readonly mutation = injectMutation(() => ({
183 mutationFn: () =>
184 sleep(10).then(() => Promise.reject(new Error('Some error'))),
185 }))
186 }
187β
188 const rendered = await render(Page)
189β
190 rendered.fixture.componentInstance.mutation.mutate()
191 await vi.advanceTimersByTimeAsync(11)
192 rendered.fixture.detectChanges()
193 expect(rendered.getByText('isError: true')).toBeInTheDocument()
194 expect(rendered.getByText('error: Some error')).toBeInTheDocument()
195β
196 rendered.fixture.componentInstance.mutation.reset()
197 await vi.advanceTimersByTimeAsync(0)
198 rendered.fixture.detectChanges()
199 expect(rendered.getByText('isIdle: true')).toBeInTheDocument()
200 expect(rendered.getByText('isPending: false')).toBeInTheDocument()
201 expect(rendered.getByText('isError: false')).toBeInTheDocument()
202 expect(rendered.getByText('isSuccess: false')).toBeInTheDocument()
203 expect(rendered.getByText('data: none')).toBeInTheDocument()
204 expect(rendered.getByText('error: none')).toBeInTheDocument()
205 })
206β
207 describe('side effects', () => {
208 beforeEach(() => {
209 vi.clearAllMocks()
210 })
211β
212 it('should call onMutate when passed as an option', async () => {
213 const onMutate =
214 vi.fn<(variables: string, context: MutationFunctionContext) => void>()
215 const mutation = TestBed.runInInjectionContext(() => {
216 return injectMutation(() => ({
217 mutationFn: (params: string) => sleep(10).then(() => params),
218 onMutate,
219 }))
220 })
221β
222 mutation.mutate('')
223 await vi.advanceTimersByTimeAsync(0)
224 expect(onMutate).toHaveBeenCalledTimes(1)
225 })
226β
227 it('should call onError when passed as an option', async () => {
228 const onError =
229 vi.fn<
230 (
231 error: Error,
232 variables: string,
233 onMutateResult: unknown,
234 context: MutationFunctionContext,
235 ) => void
236 >()
237 const mutation = TestBed.runInInjectionContext(() => {
238 return injectMutation(() => ({
239 mutationFn: (_params: string) =>
240 sleep(10).then(() => Promise.reject(new Error('Some error'))),
241 onError,
242 }))
243 })
244β
245 mutation.mutate('')
246 await vi.advanceTimersByTimeAsync(10)
247 expect(onError).toHaveBeenCalledTimes(1)
248 })
249β
250 it('should call onSuccess when passed as an option', async () => {
251 const onSuccess =
252 vi.fn<
253 (
254 data: string,
255 variables: string,
256 onMutateResult: unknown,
257 context: MutationFunctionContext,
258 ) => void
259 >()
260 const mutation = TestBed.runInInjectionContext(() => {
261 return injectMutation(() => ({
262 mutationFn: (params: string) => sleep(10).then(() => params),
263 onSuccess,
264 }))
265 })
266β
267 mutation.mutate('')
268 await vi.advanceTimersByTimeAsync(10)
269 expect(onSuccess).toHaveBeenCalledTimes(1)
270 })
271β
272 it('should call onSettled when passed as an option', async () => {
273 const onSettled =
274 vi.fn<
275 (
276 data: string | undefined,
277 error: Error | null,
278 variables: string,
279 onMutateResult: unknown,
280 context: MutationFunctionContext,
281 ) => void
282 >()
283 const mutation = TestBed.runInInjectionContext(() => {
284 return injectMutation(() => ({
285 mutationFn: (params: string) => sleep(10).then(() => params),
286 onSettled,
287 }))
288 })
289β
290 mutation.mutate('')
291 await vi.advanceTimersByTimeAsync(10)
292 expect(onSettled).toHaveBeenCalledTimes(1)
293 })
294β
295 it('should call onError when passed as an argument of mutate function', async () => {
296 const onError =
297 vi.fn<
298 (
299 error: Error,
300 variables: string,
301 onMutateResult: unknown,
302 context: MutationFunctionContext,
303 ) => void
304 >()
305 const mutation = TestBed.runInInjectionContext(() => {
306 return injectMutation(() => ({
307 mutationFn: (_params: string) =>
308 sleep(10).then(() => Promise.reject(new Error('Some error'))),
309 }))
310 })
311β
312 mutation.mutate('', { onError })
313 await vi.advanceTimersByTimeAsync(10)
314 expect(onError).toHaveBeenCalledTimes(1)
315 })
316β
317 it('should call onSuccess when passed as an argument of mutate function', async () => {
318 const onSuccess =
319 vi.fn<
320 (
321 data: string,
322 variables: string,
323 onMutateResult: unknown,
324 context: MutationFunctionContext,
325 ) => void
326 >()
327 const mutation = TestBed.runInInjectionContext(() => {
328 return injectMutation(() => ({
329 mutationFn: (params: string) => sleep(10).then(() => params),
330 }))
331 })
332β
333 mutation.mutate('', { onSuccess })
334 await vi.advanceTimersByTimeAsync(10)
335 expect(onSuccess).toHaveBeenCalledTimes(1)
336 })
337β
338 it('should call onSettled when passed as an argument of mutate function', async () => {
339 const onSettled =
340 vi.fn<
341 (
342 data: string | undefined,
343 error: Error | null,
344 variables: string,
345 onMutateResult: unknown,
346 context: MutationFunctionContext,
347 ) => void
348 >()
349 const mutation = TestBed.runInInjectionContext(() => {
350 return injectMutation(() => ({
351 mutationFn: (params: string) => sleep(10).then(() => params),
352 }))
353 })
354β
355 mutation.mutate('', { onSettled })
356 await vi.advanceTimersByTimeAsync(10)
357 expect(onSettled).toHaveBeenCalledTimes(1)
358 })
359β
360 it('should call onSuccess and onSettled when passed as arguments of mutate function', async () => {
361 const callbacks: Array<string> = []
362 const mutation = TestBed.runInInjectionContext(() => {
363 return injectMutation(() => ({
364 mutationFn: (params: string) => sleep(10).then(() => params),
365 }))
366 })
367β
368 mutation.mutate('', {
369 onSuccess: () => callbacks.push('mutate.onSuccess'),
370 onSettled: () => callbacks.push('mutate.onSettled'),
371 })
372 await vi.advanceTimersByTimeAsync(10)
373 expect(callbacks).toStrictEqual(['mutate.onSuccess', 'mutate.onSettled'])
374 })
375β
376 it('should call onError and onSettled when passed as arguments of mutate function', async () => {
377 const callbacks: Array<string> = []
378 const mutation = TestBed.runInInjectionContext(() => {
379 return injectMutation(() => ({
380 mutationFn: (_params: string) =>
381 sleep(10).then(() => Promise.reject(new Error('Some error'))),
382 }))
383 })
384β
385 mutation.mutate('', {
386 onError: () => callbacks.push('mutate.onError'),
387 onSettled: () => callbacks.push('mutate.onSettled'),
388 })
389 await vi.advanceTimersByTimeAsync(10)
390 expect(callbacks).toStrictEqual(['mutate.onError', 'mutate.onSettled'])
391 })
392β
393 it('should call onSuccess and onSettled when passed as arguments of mutateAsync function', async () => {
394 const callbacks: Array<string> = []
395 const mutation = TestBed.runInInjectionContext(() => {
396 return injectMutation(() => ({
397 mutationFn: (params: string) => sleep(10).then(() => params),
398 }))
399 })
400β
401 mutation.mutateAsync('', {
402 onSuccess: () => callbacks.push('mutateAsync.onSuccess'),
403 onSettled: () => callbacks.push('mutateAsync.onSettled'),
404 })
405 await vi.advanceTimersByTimeAsync(10)
406 expect(callbacks).toStrictEqual([
407 'mutateAsync.onSuccess',
408 'mutateAsync.onSettled',
409 ])
410 })
411β
412 it('should call onError and onSettled when passed as arguments of mutateAsync function', async () => {
413 const callbacks: Array<string> = []
414 const mutation = TestBed.runInInjectionContext(() => {
415 return injectMutation(() => ({
416 mutationFn: (_params: string) =>
417 sleep(10).then(() => Promise.reject(new Error('Some error'))),
418 }))
419 })
420β
421 mutation
422 .mutateAsync('', {
423 onError: () => callbacks.push('mutateAsync.onError'),
424 onSettled: () => callbacks.push('mutateAsync.onSettled'),
425 })
426 .catch(noop)
427 await vi.advanceTimersByTimeAsync(10)
428 expect(callbacks).toStrictEqual([
429 'mutateAsync.onError',
430 'mutateAsync.onSettled',
431 ])
432 })
433β
434 it('should call onSuccess when passed as an argument of mutateAsync function', async () => {
435 const callbacks: Array<string> = []
436 const mutation = TestBed.runInInjectionContext(() => {
437 return injectMutation(() => ({
438 mutationFn: (params: string) => sleep(10).then(() => params),
439 }))
440 })
441β
442 mutation.mutateAsync('', {
443 onSuccess: () => callbacks.push('mutateAsync.onSuccess'),
444 })
445 await vi.advanceTimersByTimeAsync(10)
446 expect(callbacks).toStrictEqual(['mutateAsync.onSuccess'])
447 })
448β
449 it('should call onError when passed as an argument of mutateAsync function', async () => {
450 const callbacks: Array<string> = []
451 const mutation = TestBed.runInInjectionContext(() => {
452 return injectMutation(() => ({
453 mutationFn: (_params: string) =>
454 sleep(10).then(() => Promise.reject(new Error('Some error'))),
455 }))
456 })
457β
458 mutation
459 .mutateAsync('', {
460 onError: () => callbacks.push('mutateAsync.onError'),
461 })
462 .catch(noop)
463 await vi.advanceTimersByTimeAsync(10)
464 expect(callbacks).toStrictEqual(['mutateAsync.onError'])
465 })
466β
467 it('should call onSettled when passed as an argument of mutateAsync function', async () => {
468 const callbacks: Array<string> = []
469 const mutation = TestBed.runInInjectionContext(() => {
470 return injectMutation(() => ({
471 mutationFn: (params: string) => sleep(10).then(() => params),
472 }))
473 })
474β
475 mutation.mutateAsync('', {
476 onSettled: () => callbacks.push('mutateAsync.onSettled'),
477 })
478 await vi.advanceTimersByTimeAsync(10)
479 expect(callbacks).toStrictEqual(['mutateAsync.onSettled'])
480 })
481β
482 it('should fire both onSettled functions', async () => {
483 const onSettled =
484 vi.fn<
485 (
486 data: string | undefined,
487 error: Error | null,
488 variables: string,
489 onMutateResult: unknown,
490 context: MutationFunctionContext,
491 ) => void
492 >()
493 const onSettledMutate =
494 vi.fn<
495 (
496 data: string | undefined,
497 error: Error | null,
498 variables: string,
499 onMutateResult: unknown,
500 context: MutationFunctionContext,
501 ) => void
502 >()
503 const mutation = TestBed.runInInjectionContext(() => {
504 return injectMutation(() => ({
505 mutationFn: (params: string) => sleep(10).then(() => params),
506 onSettled,
507 }))
508 })
509β
510 mutation.mutate('', { onSettled: onSettledMutate })
511 await vi.advanceTimersByTimeAsync(10)
512 expect(onSettled).toHaveBeenCalledTimes(1)
513 expect(onSettledMutate).toHaveBeenCalledTimes(1)
514 })
515β
516 it('should pass a non-undefined onMutateResult alongside context to onSuccess', async () => {
517 const onSuccess =
518 vi.fn<
519 (
520 data: string,
521 variables: string,
522 onMutateResult: { startedWith: string },
523 context: MutationFunctionContext,
524 ) => void
525 >()
526 const mutation = TestBed.runInInjectionContext(() => {
527 return injectMutation(() => ({
528 mutationFn: (text: string) =>
529 sleep(10).then(() => text.toUpperCase()),
530 onMutate: (text: string) => ({ startedWith: text }),
531 onSuccess,
532 }))
533 })
534β
535 mutation.mutate('todo')
536 await vi.advanceTimersByTimeAsync(10)
537 expect(onSuccess).toHaveBeenCalledTimes(1)
538 const [data, variables, onMutateResult, context] =
539 onSuccess.mock.calls[0]!
540 expect(data).toBe('TODO')
541 expect(variables).toBe('todo')
542 expect(onMutateResult).toStrictEqual({ startedWith: 'todo' })
543 expect(context.client).toBe(queryClient)
544 expect(context.meta).toBeUndefined()
545 expect(context.mutationKey).toBeUndefined()
546 })
547β
548 it('should give mutationFn the same QueryClient instance via context', async () => {
549 const key = createKey()
550 queryClient.setQueryData(key, 'tag-from-this-client')
551β
552 @Component({
553 template: `<div>data: {{ mutation.data() ?? 'none' }}</div>`,
554 })
555 class Page {
556 readonly mutation = injectMutation(() => ({
557 mutationFn: (_text: string, context) =>
558 sleep(10).then(() => context.client.getQueryData(key)),
559 }))
560 }
561β
562 const rendered = await render(Page)
563β
564 rendered.fixture.componentInstance.mutation.mutate('todo')
565 await vi.advanceTimersByTimeAsync(11)
566 rendered.fixture.detectChanges()
567 expect(
568 rendered.getByText('data: tag-from-this-client'),
569 ).toBeInTheDocument()
570 })
571β
572 it('should include mutationKey in the context passed to hook-level callbacks', async () => {
573 const onSuccess =
574 vi.fn<
575 (
576 data: string,
577 variables: string,
578 onMutateResult: unknown,
579 context: MutationFunctionContext,
580 ) => void
581 >()
582 const mutation = TestBed.runInInjectionContext(() => {
583 return injectMutation(() => ({
584 mutationKey: ['todos', 'add'],
585 mutationFn: (text: string) => sleep(10).then(() => text),
586 onSuccess,
587 }))
588 })
589β
590 mutation.mutate('todo')
591 await vi.advanceTimersByTimeAsync(10)
592 expect(onSuccess).toHaveBeenCalledTimes(1)
593 expect(onSuccess.mock.calls[0]?.[3].mutationKey).toStrictEqual([
594 'todos',
595 'add',
596 ])
597 })
598β
599 it('should let onSuccess invalidate queries via context.client without an injected QueryClient', async () => {
600 const key = createKey()
601 queryClient.setQueryData(key, 'data')
602β
603 const mutation = TestBed.runInInjectionContext(() => {
604 return injectMutation(() => ({
605 mutationFn: () => sleep(10).then(() => 'mutated'),
606 onSuccess: (_data, _variables, _onMutateResult, context) => {
607 context.client.invalidateQueries({ queryKey: key })
608 },
609 }))
610 })
611β
612 expect(queryClient.getQueryState(key)?.isInvalidated).toBe(false)
613β
614 mutation.mutate()
615 await vi.advanceTimersByTimeAsync(10)
616 expect(queryClient.getQueryState(key)?.isInvalidated).toBe(true)
617 })
618β
619 it('should give a per-call onSuccess the same QueryClient instance via context', async () => {
620 const onSuccessMutate =
621 vi.fn<
622 (
623 data: string,
624 variables: string,
625 onMutateResult: unknown,
626 context: MutationFunctionContext,
627 ) => void
628 >()
629 const mutation = TestBed.runInInjectionContext(() => {
630 return injectMutation(() => ({
631 mutationFn: (text: string) => sleep(10).then(() => text),
632 }))
633 })
634β
635 mutation.mutate('todo', { onSuccess: onSuccessMutate })
636 await vi.advanceTimersByTimeAsync(10)
637 expect(onSuccessMutate).toHaveBeenCalledTimes(1)
638 expect(onSuccessMutate.mock.calls[0]?.[3].client).toBe(queryClient)
639 })
640 })
641β
642 it('should support required signal inputs', async () => {
643 const mutationCache = queryClient.getMutationCache()
644β
645 @Component({
646 selector: 'app-fake',
647 template: `
648 <button (click)="mutate()"></button>
649 <span>{{ mutation.data() }}</span>
650 `,
651 })
652 class FakeComponent {
653 name = input.required<string>()
654β
655 mutation = injectMutation(() => ({
656 mutationKey: ['fake', this.name()],
657 mutationFn: () => sleep(10).then(() => this.name()),
658 }))
659β
660 mutate(): void {
661 this.mutation.mutate()
662 }
663 }
664β
665 const fixture = TestBed.createComponent(FakeComponent)
666 const { debugElement } = fixture
667 setFixtureSignalInputs(fixture, { name: 'value' })
668β
669 const button = debugElement.query(By.css('button'))
670 button.triggerEventHandler('click')
671 await vi.advanceTimersByTimeAsync(11)
672 fixture.detectChanges()
673β
674 const text = debugElement.query(By.css('span')).nativeElement.textContent
675 expect(text).toBe('value')
676 const mutation = mutationCache.find({ mutationKey: ['fake', 'value'] })
677 expect(mutation?.options.mutationKey).toStrictEqual(['fake', 'value'])
678 })
679β
680 it('should update options on required signal input change', async () => {
681 const mutationCache = queryClient.getMutationCache()
682β
683 @Component({
684 selector: 'app-fake',
685 template: `
686 <button (click)="mutate()"></button>
687 <span>{{ mutation.data() }}</span>
688 `,
689 })
690 class FakeComponent {
691 name = input.required<string>()
692β
693 mutation = injectMutation(() => ({
694 mutationKey: ['fake', this.name()],
695 mutationFn: () => sleep(10).then(() => this.name()),
696 }))
697β
698 mutate(): void {
699 this.mutation.mutate()
700 }
701 }
702β
703 const fixture = TestBed.createComponent(FakeComponent)
704 const { debugElement } = fixture
705 setFixtureSignalInputs(fixture, { name: 'value' })
706β
707 const button = debugElement.query(By.css('button'))
708 const span = debugElement.query(By.css('span'))
709β
710 button.triggerEventHandler('click')
711 await vi.advanceTimersByTimeAsync(11)
712 fixture.detectChanges()
713 expect(span.nativeElement.textContent).toBe('value')
714β
715 setFixtureSignalInputs(fixture, { name: 'updatedValue' })
716β
717 button.triggerEventHandler('click')
718 await vi.advanceTimersByTimeAsync(11)
719 fixture.detectChanges()
720 expect(span.nativeElement.textContent).toBe('updatedValue')
721β
722 const mutations = mutationCache.findAll()
723 expect(mutations).toHaveLength(2)
724 const [mutation1, mutation2] = mutations
725 expect(mutation1!.options.mutationKey).toStrictEqual(['fake', 'value'])
726 expect(mutation2!.options.mutationKey).toStrictEqual([
727 'fake',
728 'updatedValue',
729 ])
730 })
731β
732 describe('throwOnError', () => {
733 it('should evaluate throwOnError when mutation is expected to throw', async () => {
734 const key = createKey()
735 const err = new Error('Expected mock error. All is well!')
736 const throwOnError = vi.fn<(error: Error) => boolean>()
737 const { mutate } = TestBed.runInInjectionContext(() => {
738 return injectMutation(() => ({
739 mutationKey: key,
740 mutationFn: () => {
741 return Promise.reject(err)
742 },
743 throwOnError,
744 }))
745 })
746β
747 TestBed.tick()
748β
749 mutate()
750 await vi.advanceTimersByTimeAsync(0)
751 expect(throwOnError).toHaveBeenCalledTimes(1)
752 expect(throwOnError).toHaveBeenCalledWith(err)
753 })
754β
755 it('should throw when throwOnError is true and mutate is used', async () => {
756 const key = createKey()
757 const { mutate } = TestBed.runInInjectionContext(() => {
758 return injectMutation(() => ({
759 mutationKey: key,
760 mutationFn: () => {
761 return Promise.reject(
762 new Error('Expected mock error. All is well!'),
763 )
764 },
765 throwOnError: true,
766 }))
767 })
768β
769 TestBed.tick()
770β
771 mutate()
772 await expect(vi.advanceTimersByTimeAsync(0)).rejects.toThrow(
773 'Expected mock error. All is well!',
774 )
775 })
776 })
777β
778 it('should throw when throwOnError is true', async () => {
779 const key = createKey()
780 const err = new Error('Expected mock error. All is well!')
781 const { mutateAsync } = TestBed.runInInjectionContext(() => {
782 return injectMutation(() => ({
783 mutationKey: key,
784 mutationFn: () => {
785 return Promise.reject(err)
786 },
787 throwOnError: true,
788 }))
789 })
790β
791 await expect(() => mutateAsync()).rejects.toThrow(err)
792 })
793β
794 it('should throw when throwOnError function returns true', async () => {
795 const key = createKey()
796 const err = new Error('Expected mock error. All is well!')
797 const { mutateAsync } = TestBed.runInInjectionContext(() => {
798 return injectMutation(() => ({
799 mutationKey: key,
800 mutationFn: () => {
801 return Promise.reject(err)
802 },
803 throwOnError: () => true,
804 }))
805 })
806β
807 await expect(() => mutateAsync()).rejects.toThrow(err)
808 })
809β
810 it('should resolve mutateAsync with the value returned from mutationFn', async () => {
811 const key = createKey()
812 const { mutateAsync } = TestBed.runInInjectionContext(() => {
813 return injectMutation(() => ({
814 mutationKey: key,
815 mutationFn: (params: string) => sleep(10).then(() => params),
816 }))
817 })
818β
819 const promise = mutateAsync('Mock data')
820 await vi.advanceTimersByTimeAsync(10)
821 await expect(promise).resolves.toBe('Mock data')
822 })
823β
824 describe('injection context', () => {
825 it('should throw NG0203 with descriptive error outside injection context', () => {
826 const key = createKey()
827 expect(() => {
828 injectMutation(() => ({
829 mutationKey: key,
830 mutationFn: () => Promise.resolve(),
831 }))
832 }).toThrow(/NG0203(.*?)injectMutation/)
833 })
834β
835 it('should be usable outside injection context when passing an injector', () => {
836 const key = createKey()
837 expect(() => {
838 injectMutation(
839 () => ({
840 mutationKey: key,
841 mutationFn: () => Promise.resolve(),
842 }),
843 {
844 injector: TestBed.inject(Injector),
845 },
846 )
847 }).not.toThrow()
848 })
849β
850 it('should complete mutation before whenStable() resolves', async () => {
851 const app = TestBed.inject(ApplicationRef)
852 let mutationStarted = false
853 let mutationCompleted = false
854β
855 const key = createKey()
856 const mutation = TestBed.runInInjectionContext(() =>
857 injectMutation(() => ({
858 mutationKey: key,
859 mutationFn: async (data: string) => {
860 mutationStarted = true
861 await sleep(50)
862 mutationCompleted = true
863 return `processed: ${data}`
864 },
865 })),
866 )
867β
868 // Initial state
869 expect(mutation.data()).toBeUndefined()
870 expect(mutationStarted).toBe(false)
871β
872 // Start mutation
873 mutation.mutate('test')
874β
875 // Wait for mutation to start and Angular to be "stable"
876 const stablePromise = app.whenStable()
877 await vi.advanceTimersByTimeAsync(60)
878 await stablePromise
879β
880 // After whenStable(), mutation should be complete
881 expect(mutationStarted).toBe(true)
882 expect(mutationCompleted).toBe(true)
883 expect(mutation.isSuccess()).toBe(true)
884 expect(mutation.data()).toBe('processed: test')
885 })
886β
887 it('should handle synchronous mutation with retry', async () => {
888 const app = TestBed.inject(ApplicationRef)
889 let attemptCount = 0
890β
891 const mutation = TestBed.runInInjectionContext(() =>
892 injectMutation(() => ({
893 retry: 2,
894 retryDelay: 0, // No delay for synchronous retry
895 mutationFn: async (data: string) => {
896 attemptCount++
897 if (attemptCount <= 2) {
898 throw new Error(`Sync attempt ${attemptCount} failed`)
899 }
900 return `processed: ${data}`
901 },
902 })),
903 )
904β
905 // Start mutation
906 mutation.mutate('retry-test')
907β
908 // Synchronize pending effects for each retry attempt
909 TestBed.tick()
910 await Promise.resolve()
911 await vi.advanceTimersByTimeAsync(10)
912 TestBed.tick()
913 await Promise.resolve()
914 await vi.advanceTimersByTimeAsync(10)
915 TestBed.tick()
916β
917 const stablePromise = app.whenStable()
918 await Promise.resolve()
919 await vi.advanceTimersByTimeAsync(10)
920 await stablePromise
921 expect(mutation.isSuccess()).toBe(true)
922 expect(mutation.data()).toBe('processed: retry-test')
923 expect(attemptCount).toBe(3) // Initial + 2 retries
924 })
925β
926 it('should handle multiple synchronous mutations on same key', async () => {
927 const app = TestBed.inject(ApplicationRef)
928 let callCount = 0
929β
930 const key = createKey()
931β
932 const mutation1 = TestBed.runInInjectionContext(() =>
933 injectMutation(() => ({
934 mutationKey: key,
935 mutationFn: async (data: string) => {
936 callCount++
937 return `mutation1: ${data}`
938 },
939 })),
940 )
941β
942 const mutation2 = TestBed.runInInjectionContext(() =>
943 injectMutation(() => ({
944 mutationKey: key,
945 mutationFn: async (data: string) => {
946 callCount++
947 return `mutation2: ${data}`
948 },
949 })),
950 )
951β
952 // Start both mutations
953 mutation1.mutate('test1')
954 mutation2.mutate('test2')
955β
956 // Synchronize pending effects
957 TestBed.tick()
958β
959 const stablePromise = app.whenStable()
960 // Flush microtasks to allow TanStack Query's scheduled notifications to process
961 await Promise.resolve()
962 await vi.advanceTimersByTimeAsync(1)
963 await stablePromise
964 expect(mutation1.isSuccess()).toBe(true)
965 expect(mutation1.data()).toBe('mutation1: test1')
966 expect(mutation2.isSuccess()).toBe(true)
967 expect(mutation2.data()).toBe('mutation2: test2')
968 expect(callCount).toBe(2)
969 })
970β
971 it('should handle synchronous mutation with optimistic updates', async () => {
972 const app = TestBed.inject(ApplicationRef)
973 const testQueryKey = createKey()
974 let onMutateCalled = false
975 let onSuccessCalled = false
976β
977 // Set initial data
978 queryClient.setQueryData(testQueryKey, 'initial')
979β
980 const mutation = TestBed.runInInjectionContext(() =>
981 injectMutation(() => ({
982 mutationFn: async (data: string) => `final: ${data}`, // Synchronous resolution
983 onMutate: async (variables) => {
984 onMutateCalled = true
985 const previousData = queryClient.getQueryData(testQueryKey)
986 queryClient.setQueryData(testQueryKey, `optimistic: ${variables}`)
987 return { previousData }
988 },
989 onSuccess: (data) => {
990 onSuccessCalled = true
991 queryClient.setQueryData(testQueryKey, data)
992 },
993 })),
994 )
995β
996 // Start mutation
997 mutation.mutate('test')
998β
999 // Synchronize pending effects
1000 TestBed.tick()
1001β
1002 const stablePromise = app.whenStable()
1003 // Flush microtasks to allow TanStack Query's scheduled notifications to process
1004 await Promise.resolve()
1005 await vi.advanceTimersByTimeAsync(1)
1006 await stablePromise
1007 expect(onMutateCalled).toBe(true)
1008 expect(onSuccessCalled).toBe(true)
1009 expect(mutation.isSuccess()).toBe(true)
1010 expect(mutation.data()).toBe('final: test')
1011 expect(queryClient.getQueryData(testQueryKey)).toBe('final: test')
1012 })
1013β
1014 it('should handle synchronous mutation cancellation', async () => {
1015 const app = TestBed.inject(ApplicationRef)
1016β
1017 const key = createKey()
1018 const mutation = TestBed.runInInjectionContext(() =>
1019 injectMutation(() => ({
1020 mutationKey: key,
1021 mutationFn: async (data: string) => `processed: ${data}`, // Synchronous resolution
1022 })),
1023 )
1024β
1025 // Start mutation
1026 mutation.mutate('test')
1027β
1028 // Synchronize pending effects
1029 TestBed.tick()
1030β
1031 const stablePromise = app.whenStable()
1032 // Flush microtasks to allow TanStack Query's scheduled notifications to process
1033 await Promise.resolve()
1034 await vi.advanceTimersByTimeAsync(1)
1035 await stablePromise
1036β
1037 // Synchronous mutations complete immediately
1038 expect(mutation.isSuccess()).toBe(true)
1039 expect(mutation.data()).toBe('processed: test')
1040 })
1041 })
1042β
1043 describe('optimistic updates', () => {
1044 it('should update the cache in onMutate and roll back via onMutateResult in onError', async () => {
1045 const key = createKey()
1046 queryClient.setQueryData<Array<string>>(key, ['Todo 1'])
1047β
1048 @Component({
1049 template: `<div>isError: {{ mutation.isError() }}</div>`,
1050 })
1051 class Page {
1052 readonly mutation = injectMutation(() => ({
1053 mutationFn: () =>
1054 sleep(10).then(() => Promise.reject(new Error('Some error'))),
1055 onMutate: async (newTodo: string) => {
1056 await queryClient.cancelQueries({ queryKey: key })
1057 const previousTodos = queryClient.getQueryData<Array<string>>(key)
1058β
1059 queryClient.setQueryData<Array<string>>(key, (old) => [
1060 ...(old ?? []),
1061 newTodo,
1062 ])
1063β
1064 return { previousTodos }
1065 },
1066 onError: (_err, _newTodo, onMutateResult) => {
1067 queryClient.setQueryData(key, onMutateResult?.previousTodos)
1068 },
1069 }))
1070 }
1071β
1072 const rendered = await render(Page)
1073β
1074 rendered.fixture.componentInstance.mutation.mutate('Todo 2')
1075 // onMutate runs synchronously up to its first await, so the optimistic
1076 // value is visible immediately, before the mutationFn settles.
1077 await vi.advanceTimersByTimeAsync(0)
1078 expect(queryClient.getQueryData(key)).toStrictEqual(['Todo 1', 'Todo 2'])
1079 await vi.advanceTimersByTimeAsync(11)
1080 rendered.fixture.detectChanges()
1081 expect(rendered.getByText('isError: true')).toBeInTheDocument()
1082 expect(queryClient.getQueryData(key)).toStrictEqual(['Todo 1'])
1083 })
1084β
1085 it('should keep the optimistic update in place when the mutation succeeds', async () => {
1086 const key = createKey()
1087 queryClient.setQueryData<Array<string>>(key, ['Todo 1'])
1088β
1089 @Component({
1090 template: `<div>isSuccess: {{ mutation.isSuccess() }}</div>`,
1091 })
1092 class Page {
1093 readonly mutation = injectMutation(() => ({
1094 mutationFn: (newTodo: string) => sleep(10).then(() => newTodo),
1095 onMutate: async (newTodo: string) => {
1096 await queryClient.cancelQueries({ queryKey: key })
1097 const previousTodos = queryClient.getQueryData<Array<string>>(key)
1098β
1099 queryClient.setQueryData<Array<string>>(key, (old) => [
1100 ...(old ?? []),
1101 newTodo,
1102 ])
1103β
1104 return { previousTodos }
1105 },
1106 onError: (_err, _newTodo, onMutateResult) => {
1107 queryClient.setQueryData(key, onMutateResult?.previousTodos)
1108 },
1109 }))
1110 }
1111β
1112 const rendered = await render(Page)
1113β
1114 rendered.fixture.componentInstance.mutation.mutate('Todo 2')
1115 await vi.advanceTimersByTimeAsync(11)
1116 rendered.fixture.detectChanges()
1117 expect(rendered.getByText('isSuccess: true')).toBeInTheDocument()
1118 expect(queryClient.getQueryData(key)).toStrictEqual(['Todo 1', 'Todo 2'])
1119 })
1120 })
1121β
1122 describe('concurrent mutate calls', () => {
1123 it('should report each mutateAsync call result independently when some fail', async () => {
1124 @Component({
1125 template: `<div>isPending: {{ mutation.isPending() }}</div>`,
1126 })
1127 class Page {
1128 readonly mutation = injectMutation(() => ({
1129 mutationFn: (todo: string) =>
1130 todo === 'bad'
1131 ? sleep(10).then(() => Promise.reject(new Error('Some error')))
1132 : sleep(10).then(() => todo),
1133 }))
1134 }
1135β
1136 const rendered = await render(Page)
1137 const todos = ['Todo 1', 'bad', 'Todo 3']
1138β
1139 expect(rendered.getByText('isPending: false')).toBeInTheDocument()
1140β
1141 const settledPromise = Promise.allSettled(
1142 todos.map((todo) =>
1143 rendered.fixture.componentInstance.mutation.mutateAsync(todo),
1144 ),
1145 )
1146 await vi.advanceTimersByTimeAsync(0)
1147 rendered.fixture.detectChanges()
1148 expect(rendered.getByText('isPending: true')).toBeInTheDocument()
1149 await vi.advanceTimersByTimeAsync(11)
1150 rendered.fixture.detectChanges()
1151 const results = await settledPromise
1152β
1153 expect(results).toStrictEqual([
1154 { status: 'fulfilled', value: 'Todo 1' },
1155 { status: 'rejected', reason: Error('Some error') },
1156 { status: 'fulfilled', value: 'Todo 3' },
1157 ])
1158 expect(rendered.getByText('isPending: false')).toBeInTheDocument()
1159 })
1160β
1161 it('should only fire the per-call onSuccess for the last mutate() call', async () => {
1162 const onSuccessMutate =
1163 vi.fn<
1164 (
1165 data: string,
1166 variables: string,
1167 onMutateResult: unknown,
1168 context: MutationFunctionContext,
1169 ) => void
1170 >()
1171β
1172 @Component({
1173 template: `<div>data: {{ mutation.data() ?? 'none' }}</div>`,
1174 })
1175 class Page {
1176 readonly mutation = injectMutation(() => ({
1177 mutationFn: (todo: string) => sleep(10).then(() => todo),
1178 }))
1179 }
1180β
1181 const rendered = await render(Page)
1182β
1183 rendered.fixture.componentInstance.mutation.mutate('Todo 1', {
1184 onSuccess: onSuccessMutate,
1185 })
1186 rendered.fixture.componentInstance.mutation.mutate('Todo 2', {
1187 onSuccess: onSuccessMutate,
1188 })
1189 await vi.advanceTimersByTimeAsync(11)
1190 rendered.fixture.detectChanges()
1191 expect(onSuccessMutate).toHaveBeenCalledTimes(1)
1192 expect(onSuccessMutate).toHaveBeenCalledWith(
1193 'Todo 2',
1194 'Todo 2',
1195 undefined,
1196 expect.anything(),
1197 )
1198 expect(rendered.getByText('data: Todo 2')).toBeInTheDocument()
1199 })
1200 })
1201})