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

inject-mutation.test.ts

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