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

inject-mutation.test.ts

510 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', async () => {
55 const result = 'Mock data'
56​
57 const mutation = TestBed.runInInjectionContext(() => {
58 return injectMutation(() => ({
59 mutationFn: (params: string) => successMutator(params),
60 }))
61 })
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: errorMutator,
80 }))
81 })
82 mutation.mutate({})
83​
84 await resolveMutations()
85​
86 expectSignals(mutation, {
87 isIdle: false,
88 isPending: false,
89 isError: true,
90 isSuccess: false,
91 data: undefined,
92 error: Error('Some error'),
93 })
94 })
95​
96 test('should return data when request succeeds', async () => {
97 const result = 'Mock data'
98 const mutation = TestBed.runInInjectionContext(() => {
99 return injectMutation(() => ({
100 mutationFn: (params: string) => successMutator(params),
101 }))
102 })
103​
104 mutation.mutate(result)
105​
106 await resolveMutations()
107​
108 expectSignals(mutation, {
109 isIdle: false,
110 isPending: false,
111 isError: false,
112 isSuccess: true,
113 data: result,
114 error: null,
115 })
116 })
117​
118 test('reactive options should update mutation', async () => {
119 const mutationCache = queryClient.getMutationCache()
120 // Signal will be updated before the mutation is called
121 // this test confirms that the mutation uses the updated value
122 const mutationKey = signal(['1'])
123 const mutation = TestBed.runInInjectionContext(() => {
124 return injectMutation(() => ({
125 mutationKey: mutationKey(),
126 mutationFn: (params: string) => successMutator(params),
127 }))
128 })
129​
130 mutationKey.set(['2'])
131​
132 TestBed.flushEffects()
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: (params: string) => errorMutator(params),
145 }))
146 })
147​
148 mutation.mutate('')
149​
150 await resolveMutations()
151​
152 expect(mutation.isError()).toBe(true)
153​
154 mutation.reset()
155​
156 await resolveMutations()
157​
158 expectSignals(mutation, {
159 isIdle: true,
160 isPending: false,
161 isError: false,
162 isSuccess: false,
163 data: undefined,
164 error: null,
165 })
166 })
167​
168 describe('side effects', () => {
169 beforeEach(() => {
170 vi.clearAllMocks()
171 })
172​
173 test('should call onMutate when passed as an option', async () => {
174 const onMutate = vi.fn()
175 const mutation = TestBed.runInInjectionContext(() => {
176 return injectMutation(() => ({
177 mutationFn: (params: string) => successMutator(params),
178 onMutate,
179 }))
180 })
181​
182 mutation.mutate('')
183​
184 await resolveMutations()
185​
186 expect(onMutate).toHaveBeenCalledTimes(1)
187 })
188​
189 test('should call onError when passed as an option', async () => {
190 const onError = vi.fn()
191 const mutation = TestBed.runInInjectionContext(() => {
192 return injectMutation(() => ({
193 mutationFn: (params: string) => errorMutator(params),
194 onError,
195 }))
196 })
197​
198 mutation.mutate('')
199​
200 await resolveMutations()
201​
202 expect(onError).toHaveBeenCalledTimes(1)
203 })
204​
205 test('should call onSuccess when passed as an option', async () => {
206 const onSuccess = vi.fn()
207 const mutation = TestBed.runInInjectionContext(() => {
208 return injectMutation(() => ({
209 mutationFn: (params: string) => successMutator(params),
210 onSuccess,
211 }))
212 })
213​
214 mutation.mutate('')
215​
216 await resolveMutations()
217​
218 expect(onSuccess).toHaveBeenCalledTimes(1)
219 })
220​
221 test('should call onSettled when passed as an option', async () => {
222 const onSettled = vi.fn()
223 const mutation = TestBed.runInInjectionContext(() => {
224 return injectMutation(() => ({
225 mutationFn: (params: string) => successMutator(params),
226 onSettled,
227 }))
228 })
229​
230 mutation.mutate('')
231​
232 await resolveMutations()
233​
234 expect(onSettled).toHaveBeenCalledTimes(1)
235 })
236​
237 test('should call onError when passed as an argument of mutate function', async () => {
238 const onError = vi.fn()
239 const mutation = TestBed.runInInjectionContext(() => {
240 return injectMutation(() => ({
241 mutationFn: (params: string) => errorMutator(params),
242 }))
243 })
244​
245 mutation.mutate('', { onError })
246​
247 await resolveMutations()
248​
249 expect(onError).toHaveBeenCalledTimes(1)
250 })
251​
252 test('should call onSuccess when passed as an argument of mutate function', async () => {
253 const onSuccess = vi.fn()
254 const mutation = TestBed.runInInjectionContext(() => {
255 return injectMutation(() => ({
256 mutationFn: (params: string) => successMutator(params),
257 }))
258 })
259​
260 mutation.mutate('', { onSuccess })
261​
262 await resolveMutations()
263​
264 expect(onSuccess).toHaveBeenCalledTimes(1)
265 })
266​
267 test('should call onSettled when passed as an argument of mutate function', async () => {
268 const onSettled = vi.fn()
269 const mutation = TestBed.runInInjectionContext(() => {
270 return injectMutation(() => ({
271 mutationFn: (params: string) => successMutator(params),
272 }))
273 })
274​
275 mutation.mutate('', { onSettled })
276​
277 await resolveMutations()
278​
279 expect(onSettled).toHaveBeenCalledTimes(1)
280 })
281​
282 test('should fire both onSettled functions', async () => {
283 const onSettled = vi.fn()
284 const onSettledOnFunction = vi.fn()
285 const mutation = TestBed.runInInjectionContext(() => {
286 return injectMutation(() => ({
287 mutationFn: (params: string) => successMutator(params),
288 onSettled,
289 }))
290 })
291​
292 mutation.mutate('', { onSettled: onSettledOnFunction })
293​
294 await resolveMutations()
295​
296 expect(onSettled).toHaveBeenCalledTimes(1)
297 expect(onSettledOnFunction).toHaveBeenCalledTimes(1)
298 })
299 })
300​
301 test('should support required signal inputs', async () => {
302 const mutationCache = queryClient.getMutationCache()
303​
304 @Component({
305 selector: 'app-fake',
306 template: `
307 <button (click)="mutate()"></button>
308 <span>{{ mutation.data() }}</span>
309 `,
310 standalone: true,
311 })
312 class FakeComponent {
313 name = input.required<string>()
314​
315 mutation = injectMutation(() => ({
316 mutationKey: ['fake', this.name()],
317 mutationFn: () => successMutator(this.name()),
318 }))
319​
320 mutate(): void {
321 this.mutation.mutate()
322 }
323 }
324​
325 const fixture = TestBed.createComponent(FakeComponent)
326 const { debugElement } = fixture
327 setFixtureSignalInputs(fixture, { name: 'value' })
328​
329 const button = debugElement.query(By.css('button'))
330 button.triggerEventHandler('click')
331​
332 await resolveMutations()
333 fixture.detectChanges()
334​
335 const text = debugElement.query(By.css('span')).nativeElement.textContent
336 expect(text).toEqual('value')
337 const mutation = mutationCache.find({ mutationKey: ['fake', 'value'] })
338 expect(mutation).toBeDefined()
339 expect(mutation!.options.mutationKey).toStrictEqual(['fake', 'value'])
340 })
341​
342 test('should update options on required signal input change', async () => {
343 const mutationCache = queryClient.getMutationCache()
344​
345 @Component({
346 selector: 'app-fake',
347 template: `
348 <button (click)="mutate()"></button>
349 <span>{{ mutation.data() }}</span>
350 `,
351 standalone: true,
352 })
353 class FakeComponent {
354 name = input.required<string>()
355​
356 mutation = injectMutation(() => ({
357 mutationKey: ['fake', this.name()],
358 mutationFn: () => successMutator(this.name()),
359 }))
360​
361 mutate(): void {
362 this.mutation.mutate()
363 }
364 }
365​
366 const fixture = TestBed.createComponent(FakeComponent)
367 const { debugElement } = fixture
368 setFixtureSignalInputs(fixture, { name: 'value' })
369​
370 const button = debugElement.query(By.css('button'))
371 const span = debugElement.query(By.css('span'))
372​
373 button.triggerEventHandler('click')
374 await resolveMutations()
375 fixture.detectChanges()
376​
377 expect(span.nativeElement.textContent).toEqual('value')
378​
379 setFixtureSignalInputs(fixture, { name: 'updatedValue' })
380​
381 button.triggerEventHandler('click')
382 await resolveMutations()
383 fixture.detectChanges()
384​
385 expect(span.nativeElement.textContent).toEqual('updatedValue')
386​
387 const mutations = mutationCache.findAll()
388 expect(mutations.length).toBe(2)
389 const [mutation1, mutation2] = mutations
390 expect(mutation1!.options.mutationKey).toEqual(['fake', 'value'])
391 expect(mutation2!.options.mutationKey).toEqual(['fake', 'updatedValue'])
392 })
393​
394 describe('throwOnError', () => {
395 test('should evaluate throwOnError when mutation is expected to throw', async () => {
396 const err = new Error('Expected mock error. All is well!')
397 const boundaryFn = vi.fn()
398 const { mutate } = TestBed.runInInjectionContext(() => {
399 return injectMutation(() => ({
400 mutationKey: ['fake'],
401 mutationFn: () => {
402 return Promise.reject(err)
403 },
404 throwOnError: boundaryFn,
405 }))
406 })
407​
408 mutate()
409​
410 await resolveMutations()
411​
412 expect(boundaryFn).toHaveBeenCalledTimes(1)
413 expect(boundaryFn).toHaveBeenCalledWith(err)
414 })
415 })
416​
417 test('should throw when throwOnError is true', async () => {
418 const err = new Error('Expected mock error. All is well!')
419 const { mutateAsync } = TestBed.runInInjectionContext(() => {
420 return injectMutation(() => ({
421 mutationKey: ['fake'],
422 mutationFn: () => {
423 return Promise.reject(err)
424 },
425 throwOnError: true,
426 }))
427 })
428​
429 await expect(() => mutateAsync()).rejects.toThrowError(err)
430 })
431​
432 test('should throw when throwOnError function returns true', async () => {
433 const err = new Error('Expected mock error. All is well!')
434 const { mutateAsync } = TestBed.runInInjectionContext(() => {
435 return injectMutation(() => ({
436 mutationKey: ['fake'],
437 mutationFn: () => {
438 return Promise.reject(err)
439 },
440 throwOnError: () => true,
441 }))
442 })
443​
444 await expect(() => mutateAsync()).rejects.toThrowError(err)
445 })
446​
447 test('should execute callback in injection context', async () => {
448 const errorSpy = vi.fn()
449 @Injectable()
450 class FakeService {
451 updateData(name: string) {
452 return Promise.resolve(name)
453 }
454 }
455​
456 @Component({
457 selector: 'app-fake',
458 template: ``,
459 standalone: true,
460 providers: [FakeService],
461 })
462 class FakeComponent {
463 mutation = injectMutation(() => {
464 try {
465 const service = inject(FakeService)
466 return {
467 mutationFn: (name: string) => service.updateData(name),
468 }
469 } catch (e) {
470 errorSpy(e)
471 throw e
472 }
473 })
474 }
475​
476 const fixture = TestBed.createComponent(FakeComponent)
477 fixture.detectChanges()
478​
479 // check if injection contexts persist in a different task
480 await new Promise<void>((resolve) => queueMicrotask(() => resolve()))
481​
482 expect(
483 await fixture.componentInstance.mutation.mutateAsync('test'),
484 ).toEqual('test')
485 expect(errorSpy).not.toHaveBeenCalled()
486 })
487​
488 describe('injection context', () => {
489 test('throws NG0203 with descriptive error outside injection context', () => {
490 expect(() => {
491 injectMutation(() => ({
492 mutationKey: ['injectionContextError'],
493 mutationFn: () => Promise.resolve(),
494 }))
495 }).toThrowError(/NG0203(.*?)injectMutation/)
496 })
497​
498 test('can be used outside injection context when passing an injector', () => {
499 expect(() => {
500 injectMutation(
501 () => ({
502 mutationKey: ['injectionContextError'],
503 mutationFn: () => Promise.resolve(),
504 }),
505 TestBed.inject(Injector),
506 )
507 }).not.toThrow()
508 })
509 })
510})