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

inject-mutation.test.ts

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