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