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