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

inject-mutation.test.ts

476 lines12.8 KB

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})