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

inject-mutation.test.ts

474 lines12.5 KB

1import {
2 Component,
3 Injector,
4 input,
5 provideExperimentalZonelessChangeDetection,
6 signal,
7} from '@angular/core'
8import { TestBed } from '@angular/core/testing'
9import { describe, expect, vi } from 'vitest'
10import { By } from '@angular/platform-browser'
11import { QueryClient, injectMutation, provideTanStackQuery } from '..'
12import {
13 errorMutator,
14 expectSignals,
15 setFixtureSignalInputs,
16 successMutator,
17} from './test-utils'
18​
19const MUTATION_DURATION = 1000
20​
21const resolveMutations = () => vi.advanceTimersByTimeAsync(MUTATION_DURATION)
22​
23describe('injectMutation', () => {
24 let queryClient: QueryClient
25​
26 beforeEach(() => {
27 queryClient = new QueryClient()
28 vi.useFakeTimers()
29 TestBed.configureTestingModule({
30 providers: [
31 provideExperimentalZonelessChangeDetection(),
32 provideTanStackQuery(queryClient),
33 ],
34 })
35 })
36​
37 afterEach(() => {
38 vi.useRealTimers()
39 })
40​
41 test('should be in idle state initially', () => {
42 const mutation = TestBed.runInInjectionContext(() => {
43 return injectMutation(() => ({
44 mutationFn: (params) => successMutator(params),
45 }))
46 })
47​
48 expectSignals(mutation, {
49 isIdle: true,
50 isPending: false,
51 isError: false,
52 isSuccess: false,
53 })
54 })
55​
56 test('should change state after invoking mutate', () => {
57 const result = 'Mock data'
58​
59 const mutation = TestBed.runInInjectionContext(() => {
60 return injectMutation(() => ({
61 mutationFn: (params: string) => successMutator(params),
62 }))
63 })
64​
65 TestBed.flushEffects()
66​
67 mutation.mutate(result)
68 vi.advanceTimersByTime(1)
69​
70 expectSignals(mutation, {
71 isIdle: false,
72 isPending: true,
73 isError: false,
74 isSuccess: false,
75 data: undefined,
76 error: null,
77 })
78 })
79​
80 test('should return error when request fails', async () => {
81 const mutation = TestBed.runInInjectionContext(() => {
82 return injectMutation(() => ({
83 mutationFn: errorMutator,
84 }))
85 })
86​
87 mutation.mutate({})
88​
89 await resolveMutations()
90​
91 expectSignals(mutation, {
92 isIdle: false,
93 isPending: false,
94 isError: true,
95 isSuccess: false,
96 data: undefined,
97 error: Error('Some error'),
98 })
99 })
100​
101 test('should return data when request succeeds', async () => {
102 const result = 'Mock data'
103 const mutation = TestBed.runInInjectionContext(() => {
104 return injectMutation(() => ({
105 mutationFn: (params: string) => successMutator(params),
106 }))
107 })
108​
109 mutation.mutate(result)
110​
111 await resolveMutations()
112​
113 expectSignals(mutation, {
114 isIdle: false,
115 isPending: false,
116 isError: false,
117 isSuccess: true,
118 data: result,
119 error: null,
120 })
121 })
122​
123 test('reactive options should update mutation', async () => {
124 const mutationCache = queryClient.getMutationCache()
125 // Signal will be updated before the mutation is called
126 // this test confirms that the mutation uses the updated value
127 const mutationKey = signal(['1'])
128 const mutation = TestBed.runInInjectionContext(() => {
129 return injectMutation(() => ({
130 mutationKey: mutationKey(),
131 mutationFn: (params: string) => successMutator(params),
132 }))
133 })
134​
135 mutationKey.set(['2'])
136​
137 mutation.mutate('xyz')
138​
139 const mutations = mutationCache.find({ mutationKey: ['2'] })
140​
141 expect(mutations?.options.mutationKey).toEqual(['2'])
142 })
143​
144 test('should reset state after invoking mutation.reset', async () => {
145 const mutation = TestBed.runInInjectionContext(() => {
146 return injectMutation(() => ({
147 mutationFn: (params: string) => errorMutator(params),
148 }))
149 })
150​
151 mutation.mutate('')
152​
153 await resolveMutations()
154​
155 expect(mutation.isError()).toBe(true)
156​
157 mutation.reset()
158​
159 await resolveMutations()
160​
161 expectSignals(mutation, {
162 isIdle: true,
163 isPending: false,
164 isError: false,
165 isSuccess: false,
166 data: undefined,
167 error: null,
168 })
169 })
170​
171 describe('side effects', () => {
172 beforeEach(() => {
173 vi.clearAllMocks()
174 })
175​
176 test('should call onMutate when passed as an option', async () => {
177 const onMutate = vi.fn()
178 const mutation = TestBed.runInInjectionContext(() => {
179 return injectMutation(() => ({
180 mutationFn: (params: string) => successMutator(params),
181 onMutate,
182 }))
183 })
184​
185 mutation.mutate('')
186​
187 await resolveMutations()
188​
189 expect(onMutate).toHaveBeenCalledTimes(1)
190 })
191​
192 test('should call onError when passed as an option', async () => {
193 const onError = vi.fn()
194 const mutation = TestBed.runInInjectionContext(() => {
195 return injectMutation(() => ({
196 mutationFn: (params: string) => errorMutator(params),
197 onError,
198 }))
199 })
200​
201 mutation.mutate('')
202​
203 await resolveMutations()
204​
205 expect(onError).toHaveBeenCalledTimes(1)
206 })
207​
208 test('should call onSuccess when passed as an option', async () => {
209 const onSuccess = vi.fn()
210 const mutation = TestBed.runInInjectionContext(() => {
211 return injectMutation(() => ({
212 mutationFn: (params: string) => successMutator(params),
213 onSuccess,
214 }))
215 })
216​
217 mutation.mutate('')
218​
219 await resolveMutations()
220​
221 expect(onSuccess).toHaveBeenCalledTimes(1)
222 })
223​
224 test('should call onSettled when passed as an option', async () => {
225 const onSettled = vi.fn()
226 const mutation = TestBed.runInInjectionContext(() => {
227 return injectMutation(() => ({
228 mutationFn: (params: string) => successMutator(params),
229 onSettled,
230 }))
231 })
232​
233 mutation.mutate('')
234​
235 await resolveMutations()
236​
237 expect(onSettled).toHaveBeenCalledTimes(1)
238 })
239​
240 test('should call onError when passed as an argument of mutate function', async () => {
241 const onError = vi.fn()
242 const mutation = TestBed.runInInjectionContext(() => {
243 return injectMutation(() => ({
244 mutationFn: (params: string) => errorMutator(params),
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) => successMutator(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) => successMutator(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) => successMutator(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: () => successMutator(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: () => successMutator(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.flushEffects()
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 TestBed.inject(Injector),
470 )
471 }).not.toThrow()
472 })
473 })
474})