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

inject-mutation.test.ts

497 lines13.1 KB

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