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