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β
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: [
27 provideZonelessChangeDetection(),
28 provideTanStackQuery(queryClient),
29 ],
30 })
31 })
32β
33 afterEach(() => {
34 vi.useRealTimers()
35 })
36β
37 test('should be in idle state initially', () => {
38 const mutation = TestBed.runInInjectionContext(() => {
39 return injectMutation(() => ({
40 mutationFn: (params) => sleep(0).then(() => params),
41 }))
42 })
43β
44 expectSignals(mutation, {
45 isIdle: true,
46 isPending: false,
47 isError: false,
48 isSuccess: false,
49 })
50 })
51β
52 test('should change state after invoking mutate', () => {
53 const result = 'Mock data'
54β
55 const mutation = TestBed.runInInjectionContext(() => {
56 return injectMutation(() => ({
57 mutationFn: (params: string) => sleep(0).then(() => params),
58 }))
59 })
60β
61 TestBed.tick()
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: () =>
80 sleep(0).then(() => Promise.reject(new Error('Some error'))),
81 }))
82 })
83β
84 mutation.mutate()
85β
86 await resolveMutations()
87β
88 expectSignals(mutation, {
89 isIdle: false,
90 isPending: false,
91 isError: true,
92 isSuccess: false,
93 data: undefined,
94 error: Error('Some error'),
95 })
96 })
97β
98 test('should return data when request succeeds', async () => {
99 const result = 'Mock data'
100 const mutation = TestBed.runInInjectionContext(() => {
101 return injectMutation(() => ({
102 mutationFn: (params: string) => sleep(0).then(() => params),
103 }))
104 })
105β
106 mutation.mutate(result)
107β
108 await resolveMutations()
109β
110 expectSignals(mutation, {
111 isIdle: false,
112 isPending: false,
113 isError: false,
114 isSuccess: true,
115 data: result,
116 error: null,
117 })
118 })
119β
120 test('reactive options should update mutation', () => {
121 const mutationCache = queryClient.getMutationCache()
122 // Signal will be updated before the mutation is called
123 // this test confirms that the mutation uses the updated value
124 const mutationKey = signal(['1'])
125 const mutation = TestBed.runInInjectionContext(() => {
126 return injectMutation(() => ({
127 mutationKey: mutationKey(),
128 mutationFn: (params: string) => sleep(0).then(() => params),
129 }))
130 })
131β
132 mutationKey.set(['2'])
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: () =>
145 sleep(0).then(() => Promise.reject(new Error('Some error'))),
146 }))
147 })
148β
149 mutation.mutate()
150β
151 await resolveMutations()
152β
153 expect(mutation.isError()).toBe(true)
154β
155 mutation.reset()
156β
157 await resolveMutations()
158β
159 expectSignals(mutation, {
160 isIdle: true,
161 isPending: false,
162 isError: false,
163 isSuccess: false,
164 data: undefined,
165 error: null,
166 })
167 })
168β
169 describe('side effects', () => {
170 beforeEach(() => {
171 vi.clearAllMocks()
172 })
173β
174 test('should call onMutate when passed as an option', async () => {
175 const onMutate = vi.fn()
176 const mutation = TestBed.runInInjectionContext(() => {
177 return injectMutation(() => ({
178 mutationFn: (params: string) => sleep(0).then(() => params),
179 onMutate,
180 }))
181 })
182β
183 mutation.mutate('')
184β
185 await resolveMutations()
186β
187 expect(onMutate).toHaveBeenCalledTimes(1)
188 })
189β
190 test('should call onError when passed as an option', async () => {
191 const onError = vi.fn()
192 const mutation = TestBed.runInInjectionContext(() => {
193 return injectMutation(() => ({
194 mutationFn: (_params: string) =>
195 sleep(0).then(() => Promise.reject(new Error('Some error'))),
196 onError,
197 }))
198 })
199β
200 mutation.mutate('')
201β
202 await resolveMutations()
203β
204 expect(onError).toHaveBeenCalledTimes(1)
205 })
206β
207 test('should call onSuccess when passed as an option', async () => {
208 const onSuccess = vi.fn()
209 const mutation = TestBed.runInInjectionContext(() => {
210 return injectMutation(() => ({
211 mutationFn: (params: string) => sleep(0).then(() => params),
212 onSuccess,
213 }))
214 })
215β
216 mutation.mutate('')
217β
218 await resolveMutations()
219β
220 expect(onSuccess).toHaveBeenCalledTimes(1)
221 })
222β
223 test('should call onSettled when passed as an option', async () => {
224 const onSettled = vi.fn()
225 const mutation = TestBed.runInInjectionContext(() => {
226 return injectMutation(() => ({
227 mutationFn: (params: string) => sleep(0).then(() => params),
228 onSettled,
229 }))
230 })
231β
232 mutation.mutate('')
233β
234 await resolveMutations()
235β
236 expect(onSettled).toHaveBeenCalledTimes(1)
237 })
238β
239 test('should call onError when passed as an argument of mutate function', async () => {
240 const onError = vi.fn()
241 const mutation = TestBed.runInInjectionContext(() => {
242 return injectMutation(() => ({
243 mutationFn: (_params: string) =>
244 sleep(0).then(() => Promise.reject(new Error('Some error'))),
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) => sleep(0).then(() => 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) => sleep(0).then(() => 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) => sleep(0).then(() => 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: () => sleep(0).then(() => 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: () => sleep(0).then(() => 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.tick()
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 {
470 injector: TestBed.inject(Injector),
471 },
472 )
473 }).not.toThrow()
474 })
475 })
476})