Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

inject-mutation.test.ts

513 lines13.4 KB

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