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