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