Open History to see the last commit
1import {
2 Component,
3 Injectable,
4 Injector,
5 inject,
6 input,
7 provideExperimentalZonelessChangeDetection,
8 signal,
9} from '@angular/core'
10import { TestBed } from '@angular/core/testing'
11import { describe, expect, vi } from 'vitest'
12import { By } from '@angular/platform-browser'
13import { QueryClient, injectMutation, provideTanStackQuery } from '..'
14import {
15 errorMutator,
16 expectSignals,
17 setFixtureSignalInputs,
18 successMutator,
19} from './test-utils'
20β
21const MUTATION_DURATION = 1000
22β
23const resolveMutations = () => vi.advanceTimersByTimeAsync(MUTATION_DURATION)
24β
25describe('injectMutation', () => {
26 let queryClient: QueryClient
27β
28 beforeEach(() => {
29 queryClient = new QueryClient()
30 vi.useFakeTimers()
31 TestBed.configureTestingModule({
32 providers: [
33 provideExperimentalZonelessChangeDetection(),
34 provideTanStackQuery(queryClient),
35 ],
36 })
37 })
38β
39 afterEach(() => {
40 vi.useRealTimers()
41 })
42β
43 test('should be in idle state initially', () => {
44 const mutation = TestBed.runInInjectionContext(() => {
45 return injectMutation(() => ({
46 mutationFn: (params) => successMutator(params),
47 }))
48 })
49β
50 expectSignals(mutation, {
51 isIdle: true,
52 isPending: false,
53 isError: false,
54 isSuccess: false,
55 })
56 })
57β
58 test('should change state after invoking mutate', () => {
59 const result = 'Mock data'
60β
61 const mutation = TestBed.runInInjectionContext(() => {
62 return injectMutation(() => ({
63 mutationFn: (params: string) => successMutator(params),
64 }))
65 })
66β
67 TestBed.flushEffects()
68β
69 mutation.mutate(result)
70 vi.advanceTimersByTime(1)
71β
72 expectSignals(mutation, {
73 isIdle: false,
74 isPending: true,
75 isError: false,
76 isSuccess: false,
77 data: undefined,
78 error: null,
79 })
80 })
81β
82 test('should return error when request fails', async () => {
83 const mutation = TestBed.runInInjectionContext(() => {
84 return injectMutation(() => ({
85 mutationFn: errorMutator,
86 }))
87 })
88β
89 mutation.mutate({})
90β
91 await resolveMutations()
92β
93 expectSignals(mutation, {
94 isIdle: false,
95 isPending: false,
96 isError: true,
97 isSuccess: false,
98 data: undefined,
99 error: Error('Some error'),
100 })
101 })
102β
103 test('should return data when request succeeds', async () => {
104 const result = 'Mock data'
105 const mutation = TestBed.runInInjectionContext(() => {
106 return injectMutation(() => ({
107 mutationFn: (params: string) => successMutator(params),
108 }))
109 })
110β
111 mutation.mutate(result)
112β
113 await resolveMutations()
114β
115 expectSignals(mutation, {
116 isIdle: false,
117 isPending: false,
118 isError: false,
119 isSuccess: true,
120 data: result,
121 error: null,
122 })
123 })
124β
125 test('reactive options should update mutation', async () => {
126 const mutationCache = queryClient.getMutationCache()
127 // Signal will be updated before the mutation is called
128 // this test confirms that the mutation uses the updated value
129 const mutationKey = signal(['1'])
130 const mutation = TestBed.runInInjectionContext(() => {
131 return injectMutation(() => ({
132 mutationKey: mutationKey(),
133 mutationFn: (params: string) => successMutator(params),
134 }))
135 })
136β
137 mutationKey.set(['2'])
138β
139 mutation.mutate('xyz')
140β
141 const mutations = mutationCache.find({ mutationKey: ['2'] })
142β
143 expect(mutations?.options.mutationKey).toEqual(['2'])
144 })
145β
146 test('should reset state after invoking mutation.reset', async () => {
147 const mutation = TestBed.runInInjectionContext(() => {
148 return injectMutation(() => ({
149 mutationFn: (params: string) => errorMutator(params),
150 }))
151 })
152β
153 mutation.mutate('')
154β
155 await resolveMutations()
156β
157 expect(mutation.isError()).toBe(true)
158β
159 mutation.reset()
160β
161 await resolveMutations()
162β
163 expectSignals(mutation, {
164 isIdle: true,
165 isPending: false,
166 isError: false,
167 isSuccess: false,
168 data: undefined,
169 error: null,
170 })
171 })
172β
173 describe('side effects', () => {
174 beforeEach(() => {
175 vi.clearAllMocks()
176 })
177β
178 test('should call onMutate when passed as an option', async () => {
179 const onMutate = vi.fn()
180 const mutation = TestBed.runInInjectionContext(() => {
181 return injectMutation(() => ({
182 mutationFn: (params: string) => successMutator(params),
183 onMutate,
184 }))
185 })
186β
187 mutation.mutate('')
188β
189 await resolveMutations()
190β
191 expect(onMutate).toHaveBeenCalledTimes(1)
192 })
193β
194 test('should call onError when passed as an option', async () => {
195 const onError = vi.fn()
196 const mutation = TestBed.runInInjectionContext(() => {
197 return injectMutation(() => ({
198 mutationFn: (params: string) => errorMutator(params),
199 onError,
200 }))
201 })
202β
203 mutation.mutate('')
204β
205 await resolveMutations()
206β
207 expect(onError).toHaveBeenCalledTimes(1)
208 })
209β
210 test('should call onSuccess when passed as an option', async () => {
211 const onSuccess = vi.fn()
212 const mutation = TestBed.runInInjectionContext(() => {
213 return injectMutation(() => ({
214 mutationFn: (params: string) => successMutator(params),
215 onSuccess,
216 }))
217 })
218β
219 mutation.mutate('')
220β
221 await resolveMutations()
222β
223 expect(onSuccess).toHaveBeenCalledTimes(1)
224 })
225β
226 test('should call onSettled when passed as an option', async () => {
227 const onSettled = vi.fn()
228 const mutation = TestBed.runInInjectionContext(() => {
229 return injectMutation(() => ({
230 mutationFn: (params: string) => successMutator(params),
231 onSettled,
232 }))
233 })
234β
235 mutation.mutate('')
236β
237 await resolveMutations()
238β
239 expect(onSettled).toHaveBeenCalledTimes(1)
240 })
241β
242 test('should call onError when passed as an argument of mutate function', async () => {
243 const onError = vi.fn()
244 const mutation = TestBed.runInInjectionContext(() => {
245 return injectMutation(() => ({
246 mutationFn: (params: string) => errorMutator(params),
247 }))
248 })
249β
250 mutation.mutate('', { onError })
251β
252 await resolveMutations()
253β
254 expect(onError).toHaveBeenCalledTimes(1)
255 })
256β
257 test('should call onSuccess when passed as an argument of mutate function', async () => {
258 const onSuccess = vi.fn()
259 const mutation = TestBed.runInInjectionContext(() => {
260 return injectMutation(() => ({
261 mutationFn: (params: string) => successMutator(params),
262 }))
263 })
264β
265 mutation.mutate('', { onSuccess })
266β
267 await resolveMutations()
268β
269 expect(onSuccess).toHaveBeenCalledTimes(1)
270 })
271β
272 test('should call onSettled when passed as an argument of mutate function', async () => {
273 const onSettled = vi.fn()
274 const mutation = TestBed.runInInjectionContext(() => {
275 return injectMutation(() => ({
276 mutationFn: (params: string) => successMutator(params),
277 }))
278 })
279β
280 mutation.mutate('', { onSettled })
281β
282 await resolveMutations()
283β
284 expect(onSettled).toHaveBeenCalledTimes(1)
285 })
286β
287 test('should fire both onSettled functions', async () => {
288 const onSettled = vi.fn()
289 const onSettledOnFunction = vi.fn()
290 const mutation = TestBed.runInInjectionContext(() => {
291 return injectMutation(() => ({
292 mutationFn: (params: string) => successMutator(params),
293 onSettled,
294 }))
295 })
296β
297 mutation.mutate('', { onSettled: onSettledOnFunction })
298β
299 await resolveMutations()
300β
301 expect(onSettled).toHaveBeenCalledTimes(1)
302 expect(onSettledOnFunction).toHaveBeenCalledTimes(1)
303 })
304 })
305β
306 test('should support required signal inputs', async () => {
307 const mutationCache = queryClient.getMutationCache()
308β
309 @Component({
310 selector: 'app-fake',
311 template: `
312 <button (click)="mutate()"></button>
313 <span>{{ mutation.data() }}</span>
314 `,
315 standalone: true,
316 })
317 class FakeComponent {
318 name = input.required<string>()
319β
320 mutation = injectMutation(() => ({
321 mutationKey: ['fake', this.name()],
322 mutationFn: () => successMutator(this.name()),
323 }))
324β
325 mutate(): void {
326 this.mutation.mutate()
327 }
328 }
329β
330 const fixture = TestBed.createComponent(FakeComponent)
331 const { debugElement } = fixture
332 setFixtureSignalInputs(fixture, { name: 'value' })
333β
334 const button = debugElement.query(By.css('button'))
335 button.triggerEventHandler('click')
336β
337 await resolveMutations()
338 fixture.detectChanges()
339β
340 const text = debugElement.query(By.css('span')).nativeElement.textContent
341 expect(text).toEqual('value')
342 const mutation = mutationCache.find({ mutationKey: ['fake', 'value'] })
343 expect(mutation).toBeDefined()
344 expect(mutation!.options.mutationKey).toStrictEqual(['fake', 'value'])
345 })
346β
347 test('should update options on required signal input change', async () => {
348 const mutationCache = queryClient.getMutationCache()
349β
350 @Component({
351 selector: 'app-fake',
352 template: `
353 <button (click)="mutate()"></button>
354 <span>{{ mutation.data() }}</span>
355 `,
356 standalone: true,
357 })
358 class FakeComponent {
359 name = input.required<string>()
360β
361 mutation = injectMutation(() => ({
362 mutationKey: ['fake', this.name()],
363 mutationFn: () => successMutator(this.name()),
364 }))
365β
366 mutate(): void {
367 this.mutation.mutate()
368 }
369 }
370β
371 const fixture = TestBed.createComponent(FakeComponent)
372 const { debugElement } = fixture
373 setFixtureSignalInputs(fixture, { name: 'value' })
374β
375 const button = debugElement.query(By.css('button'))
376 const span = debugElement.query(By.css('span'))
377β
378 button.triggerEventHandler('click')
379 await resolveMutations()
380 fixture.detectChanges()
381β
382 expect(span.nativeElement.textContent).toEqual('value')
383β
384 setFixtureSignalInputs(fixture, { name: 'updatedValue' })
385β
386 button.triggerEventHandler('click')
387 await resolveMutations()
388 fixture.detectChanges()
389β
390 expect(span.nativeElement.textContent).toEqual('updatedValue')
391β
392 const mutations = mutationCache.findAll()
393 expect(mutations.length).toBe(2)
394 const [mutation1, mutation2] = mutations
395 expect(mutation1!.options.mutationKey).toEqual(['fake', 'value'])
396 expect(mutation2!.options.mutationKey).toEqual(['fake', 'updatedValue'])
397 })
398β
399 describe('throwOnError', () => {
400 test('should evaluate throwOnError when mutation is expected to throw', async () => {
401 const err = new Error('Expected mock error. All is well!')
402 const boundaryFn = vi.fn()
403 const { mutate } = TestBed.runInInjectionContext(() => {
404 return injectMutation(() => ({
405 mutationKey: ['fake'],
406 mutationFn: () => {
407 return Promise.reject(err)
408 },
409 throwOnError: boundaryFn,
410 }))
411 })
412β
413 TestBed.flushEffects()
414β
415 mutate()
416β
417 await resolveMutations()
418β
419 expect(boundaryFn).toHaveBeenCalledTimes(1)
420 expect(boundaryFn).toHaveBeenCalledWith(err)
421 })
422 })
423β
424 test('should throw when throwOnError is true', async () => {
425 const err = new Error('Expected mock error. All is well!')
426 const { mutateAsync } = TestBed.runInInjectionContext(() => {
427 return injectMutation(() => ({
428 mutationKey: ['fake'],
429 mutationFn: () => {
430 return Promise.reject(err)
431 },
432 throwOnError: true,
433 }))
434 })
435β
436 await expect(() => mutateAsync()).rejects.toThrowError(err)
437 })
438β
439 test('should throw when throwOnError function returns true', async () => {
440 const err = new Error('Expected mock error. All is well!')
441 const { mutateAsync } = TestBed.runInInjectionContext(() => {
442 return injectMutation(() => ({
443 mutationKey: ['fake'],
444 mutationFn: () => {
445 return Promise.reject(err)
446 },
447 throwOnError: () => true,
448 }))
449 })
450β
451 await expect(() => mutateAsync()).rejects.toThrowError(err)
452 })
453β
454 test('should execute callback in injection context', async () => {
455 const errorSpy = vi.fn()
456 @Injectable()
457 class FakeService {
458 updateData(name: string) {
459 return Promise.resolve(name)
460 }
461 }
462β
463 @Component({
464 selector: 'app-fake',
465 template: ``,
466 standalone: true,
467 providers: [FakeService],
468 })
469 class FakeComponent {
470 mutation = injectMutation(() => {
471 try {
472 const service = inject(FakeService)
473 return {
474 mutationFn: (name: string) => service.updateData(name),
475 }
476 } catch (e) {
477 errorSpy(e)
478 throw e
479 }
480 })
481 }
482β
483 const fixture = TestBed.createComponent(FakeComponent)
484 fixture.detectChanges()
485β
486 // check if injection contexts persist in a different task
487 await new Promise<void>((resolve) => queueMicrotask(() => resolve()))
488β
489 expect(
490 await fixture.componentInstance.mutation.mutateAsync('test'),
491 ).toEqual('test')
492 expect(errorSpy).not.toHaveBeenCalled()
493 })
494β
495 describe('injection context', () => {
496 test('throws NG0203 with descriptive error outside injection context', () => {
497 expect(() => {
498 injectMutation(() => ({
499 mutationKey: ['injectionContextError'],
500 mutationFn: () => Promise.resolve(),
501 }))
502 }).toThrowError(/NG0203(.*?)injectMutation/)
503 })
504β
505 test('can be used outside injection context when passing an injector', () => {
506 expect(() => {
507 injectMutation(
508 () => ({
509 mutationKey: ['injectionContextError'],
510 mutationFn: () => Promise.resolve(),
511 }),
512 TestBed.inject(Injector),
513 )
514 }).not.toThrow()
515 })
516 })
517})