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 })
310 class FakeComponent {
311 name = input.required<string>()
312β
313 mutation = injectMutation(() => ({
314 mutationKey: ['fake', this.name()],
315 mutationFn: () => sleep(10).then(() => this.name()),
316 }))
317β
318 mutate(): void {
319 this.mutation.mutate()
320 }
321 }
322β
323 const fixture = TestBed.createComponent(FakeComponent)
324 const { debugElement } = fixture
325 setFixtureSignalInputs(fixture, { name: 'value' })
326β
327 const button = debugElement.query(By.css('button'))
328 button.triggerEventHandler('click')
329β
330 await vi.advanceTimersByTimeAsync(11)
331 fixture.detectChanges()
332β
333 const text = debugElement.query(By.css('span')).nativeElement.textContent
334 expect(text).toEqual('value')
335 const mutation = mutationCache.find({ mutationKey: ['fake', 'value'] })
336 expect(mutation).toBeDefined()
337 expect(mutation!.options.mutationKey).toStrictEqual(['fake', 'value'])
338 })
339β
340 test('should update options on required signal input change', async () => {
341 const mutationCache = queryClient.getMutationCache()
342β
343 @Component({
344 selector: 'app-fake',
345 template: `
346 <button (click)="mutate()"></button>
347 <span>{{ mutation.data() }}</span>
348 `,
349 })
350 class FakeComponent {
351 name = input.required<string>()
352β
353 mutation = injectMutation(() => ({
354 mutationKey: ['fake', this.name()],
355 mutationFn: () => sleep(10).then(() => this.name()),
356 }))
357β
358 mutate(): void {
359 this.mutation.mutate()
360 }
361 }
362β
363 const fixture = TestBed.createComponent(FakeComponent)
364 const { debugElement } = fixture
365 setFixtureSignalInputs(fixture, { name: 'value' })
366β
367 const button = debugElement.query(By.css('button'))
368 const span = debugElement.query(By.css('span'))
369β
370 button.triggerEventHandler('click')
371 await vi.advanceTimersByTimeAsync(11)
372 fixture.detectChanges()
373β
374 expect(span.nativeElement.textContent).toEqual('value')
375β
376 setFixtureSignalInputs(fixture, { name: 'updatedValue' })
377β
378 button.triggerEventHandler('click')
379 await vi.advanceTimersByTimeAsync(11)
380 fixture.detectChanges()
381β
382 expect(span.nativeElement.textContent).toEqual('updatedValue')
383β
384 const mutations = mutationCache.findAll()
385 expect(mutations.length).toBe(2)
386 const [mutation1, mutation2] = mutations
387 expect(mutation1!.options.mutationKey).toEqual(['fake', 'value'])
388 expect(mutation2!.options.mutationKey).toEqual(['fake', 'updatedValue'])
389 })
390β
391 describe('throwOnError', () => {
392 test('should evaluate throwOnError when mutation is expected to throw', async () => {
393 const err = new Error('Expected mock error. All is well!')
394 const boundaryFn = vi.fn()
395 const { mutate } = TestBed.runInInjectionContext(() => {
396 return injectMutation(() => ({
397 mutationKey: ['fake'],
398 mutationFn: () => {
399 return Promise.reject(err)
400 },
401 throwOnError: boundaryFn,
402 }))
403 })
404β
405 TestBed.tick()
406β
407 mutate()
408β
409 await vi.advanceTimersByTimeAsync(0)
410β
411 expect(boundaryFn).toHaveBeenCalledTimes(1)
412 expect(boundaryFn).toHaveBeenCalledWith(err)
413 })
414 })
415β
416 test('should throw when throwOnError is true', async () => {
417 const err = new Error('Expected mock error. All is well!')
418 const { mutateAsync } = TestBed.runInInjectionContext(() => {
419 return injectMutation(() => ({
420 mutationKey: ['fake'],
421 mutationFn: () => {
422 return Promise.reject(err)
423 },
424 throwOnError: true,
425 }))
426 })
427β
428 await expect(() => mutateAsync()).rejects.toThrowError(err)
429 })
430β
431 test('should throw when throwOnError function returns true', async () => {
432 const err = new Error('Expected mock error. All is well!')
433 const { mutateAsync } = TestBed.runInInjectionContext(() => {
434 return injectMutation(() => ({
435 mutationKey: ['fake'],
436 mutationFn: () => {
437 return Promise.reject(err)
438 },
439 throwOnError: () => true,
440 }))
441 })
442β
443 await expect(() => mutateAsync()).rejects.toThrowError(err)
444 })
445β
446 describe('injection context', () => {
447 test('throws NG0203 with descriptive error outside injection context', () => {
448 expect(() => {
449 injectMutation(() => ({
450 mutationKey: ['injectionContextError'],
451 mutationFn: () => Promise.resolve(),
452 }))
453 }).toThrowError(/NG0203(.*?)injectMutation/)
454 })
455β
456 test('can be used outside injection context when passing an injector', () => {
457 expect(() => {
458 injectMutation(
459 () => ({
460 mutationKey: ['injectionContextError'],
461 mutationFn: () => Promise.resolve(),
462 }),
463 {
464 injector: TestBed.inject(Injector),
465 },
466 )
467 }).not.toThrow()
468 })
469 })
470})