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