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

inject-mutation.test.ts

470 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​
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 })
310 class FakeComponent {
311 name = input.required<string>()
312​
313 mutation = injectMutation(() => ({
314 mutationKey: ['fake', this.name()],
315 mutationFn: () => sleep(10).then(() => this.name()),
316 }))
317​
318 mutate(): void {
319 this.mutation.mutate()
320 }
321 }
322​
323 const fixture = TestBed.createComponent(FakeComponent)
324 const { debugElement } = fixture
325 setFixtureSignalInputs(fixture, { name: 'value' })
326​
327 const button = debugElement.query(By.css('button'))
328 button.triggerEventHandler('click')
329​
330 await vi.advanceTimersByTimeAsync(11)
331 fixture.detectChanges()
332​
333 const text = debugElement.query(By.css('span')).nativeElement.textContent
334 expect(text).toEqual('value')
335 const mutation = mutationCache.find({ mutationKey: ['fake', 'value'] })
336 expect(mutation).toBeDefined()
337 expect(mutation!.options.mutationKey).toStrictEqual(['fake', 'value'])
338 })
339​
340 test('should update options on required signal input change', async () => {
341 const mutationCache = queryClient.getMutationCache()
342​
343 @Component({
344 selector: 'app-fake',
345 template: `
346 <button (click)="mutate()"></button>
347 <span>{{ mutation.data() }}</span>
348 `,
349 })
350 class FakeComponent {
351 name = input.required<string>()
352​
353 mutation = injectMutation(() => ({
354 mutationKey: ['fake', this.name()],
355 mutationFn: () => sleep(10).then(() => this.name()),
356 }))
357​
358 mutate(): void {
359 this.mutation.mutate()
360 }
361 }
362​
363 const fixture = TestBed.createComponent(FakeComponent)
364 const { debugElement } = fixture
365 setFixtureSignalInputs(fixture, { name: 'value' })
366​
367 const button = debugElement.query(By.css('button'))
368 const span = debugElement.query(By.css('span'))
369​
370 button.triggerEventHandler('click')
371 await vi.advanceTimersByTimeAsync(11)
372 fixture.detectChanges()
373​
374 expect(span.nativeElement.textContent).toEqual('value')
375​
376 setFixtureSignalInputs(fixture, { name: 'updatedValue' })
377​
378 button.triggerEventHandler('click')
379 await vi.advanceTimersByTimeAsync(11)
380 fixture.detectChanges()
381​
382 expect(span.nativeElement.textContent).toEqual('updatedValue')
383​
384 const mutations = mutationCache.findAll()
385 expect(mutations.length).toBe(2)
386 const [mutation1, mutation2] = mutations
387 expect(mutation1!.options.mutationKey).toEqual(['fake', 'value'])
388 expect(mutation2!.options.mutationKey).toEqual(['fake', 'updatedValue'])
389 })
390​
391 describe('throwOnError', () => {
392 test('should evaluate throwOnError when mutation is expected to throw', async () => {
393 const err = new Error('Expected mock error. All is well!')
394 const boundaryFn = vi.fn()
395 const { mutate } = TestBed.runInInjectionContext(() => {
396 return injectMutation(() => ({
397 mutationKey: ['fake'],
398 mutationFn: () => {
399 return Promise.reject(err)
400 },
401 throwOnError: boundaryFn,
402 }))
403 })
404​
405 TestBed.tick()
406​
407 mutate()
408​
409 await vi.advanceTimersByTimeAsync(0)
410​
411 expect(boundaryFn).toHaveBeenCalledTimes(1)
412 expect(boundaryFn).toHaveBeenCalledWith(err)
413 })
414 })
415​
416 test('should throw when throwOnError is true', async () => {
417 const err = new Error('Expected mock error. All is well!')
418 const { mutateAsync } = TestBed.runInInjectionContext(() => {
419 return injectMutation(() => ({
420 mutationKey: ['fake'],
421 mutationFn: () => {
422 return Promise.reject(err)
423 },
424 throwOnError: true,
425 }))
426 })
427​
428 await expect(() => mutateAsync()).rejects.toThrowError(err)
429 })
430​
431 test('should throw when throwOnError function returns true', async () => {
432 const err = new Error('Expected mock error. All is well!')
433 const { mutateAsync } = TestBed.runInInjectionContext(() => {
434 return injectMutation(() => ({
435 mutationKey: ['fake'],
436 mutationFn: () => {
437 return Promise.reject(err)
438 },
439 throwOnError: () => true,
440 }))
441 })
442​
443 await expect(() => mutateAsync()).rejects.toThrowError(err)
444 })
445​
446 describe('injection context', () => {
447 test('throws NG0203 with descriptive error outside injection context', () => {
448 expect(() => {
449 injectMutation(() => ({
450 mutationKey: ['injectionContextError'],
451 mutationFn: () => Promise.resolve(),
452 }))
453 }).toThrowError(/NG0203(.*?)injectMutation/)
454 })
455​
456 test('can be used outside injection context when passing an injector', () => {
457 expect(() => {
458 injectMutation(
459 () => ({
460 mutationKey: ['injectionContextError'],
461 mutationFn: () => Promise.resolve(),
462 }),
463 {
464 injector: TestBed.inject(Injector),
465 },
466 )
467 }).not.toThrow()
468 })
469 })
470})