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