Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
2import { reactive, ref } from 'vue-demi'
3import { sleep } from '@tanstack/query-test-utils'
4import { useMutation } from '../useMutation'
5import { useQueryClient } from '../useQueryClient'
6β
7vi.mock('../useQueryClient')
8β
9describe('useMutation', () => {
10 beforeEach(() => {
11 vi.useFakeTimers()
12 })
13 afterEach(() => {
14 vi.useRealTimers()
15 })
16β
17 test('should be in idle state initially', () => {
18 const mutation = useMutation({
19 mutationFn: (params) => sleep(0).then(() => params),
20 })
21β
22 expect(mutation).toMatchObject({
23 isIdle: { value: true },
24 isPending: { value: false },
25 isError: { value: false },
26 isSuccess: { value: false },
27 })
28 })
29β
30 test('should change state after invoking mutate', () => {
31 const result = 'Mock data'
32 const mutation = useMutation({
33 mutationFn: (params: string) => sleep(0).then(() => params),
34 })
35β
36 mutation.mutate(result)
37β
38 expect(mutation).toMatchObject({
39 isIdle: { value: false },
40 isPending: { value: true },
41 isError: { value: false },
42 isSuccess: { value: false },
43 data: { value: undefined },
44 error: { value: null },
45 })
46 })
47β
48 test('should return error when request fails', async () => {
49 const mutation = useMutation({
50 mutationFn: () =>
51 sleep(10).then(() => Promise.reject(new Error('Some error'))),
52 })
53 mutation.mutate()
54 await vi.advanceTimersByTimeAsync(10)
55 expect(mutation).toMatchObject({
56 isIdle: { value: false },
57 isPending: { value: false },
58 isError: { value: true },
59 isSuccess: { value: false },
60 data: { value: undefined },
61 error: { value: Error('Some error') },
62 })
63 })
64β
65 test('should return data when request succeeds', async () => {
66 const result = 'Mock data'
67 const mutation = useMutation({
68 mutationFn: (params: string) => sleep(10).then(() => params),
69 })
70β
71 mutation.mutate(result)
72β
73 await vi.advanceTimersByTimeAsync(10)
74β
75 expect(mutation).toMatchObject({
76 isIdle: { value: false },
77 isPending: { value: false },
78 isError: { value: false },
79 isSuccess: { value: true },
80 data: { value: 'Mock data' },
81 error: { value: null },
82 })
83 })
84β
85 test('should work with options getter and be reactive', async () => {
86 const result = 'Mock data'
87 const keyRef = ref('key01')
88 const fnMock = vi.fn((params: string) => sleep(10).then(() => params))
89 const mutation = useMutation(() => ({
90 mutationKey: [keyRef.value],
91 mutationFn: fnMock,
92 }))
93β
94 mutation.mutate(result)
95β
96 await vi.advanceTimersByTimeAsync(10)
97β
98 expect(fnMock).toHaveBeenCalledTimes(1)
99 expect(fnMock).toHaveBeenNthCalledWith(
100 1,
101 result,
102 expect.objectContaining({ mutationKey: ['key01'] }),
103 )
104β
105 keyRef.value = 'key02'
106 await vi.advanceTimersByTimeAsync(0)
107 mutation.mutate(result)
108 await vi.advanceTimersByTimeAsync(10)
109β
110 expect(fnMock).toHaveBeenCalledTimes(2)
111 expect(fnMock).toHaveBeenNthCalledWith(
112 2,
113 result,
114 expect.objectContaining({ mutationKey: ['key02'] }),
115 )
116 })
117β
118 test('should update reactive options', async () => {
119 const queryClient = useQueryClient()
120 const mutationCache = queryClient.getMutationCache()
121 const options = reactive({
122 mutationKey: ['foo'],
123 mutationFn: (params: string) => sleep(10).then(() => params),
124 })
125 const mutation = useMutation(options)
126β
127 options.mutationKey = ['bar']
128 await vi.advanceTimersByTimeAsync(10)
129 mutation.mutate('xyz')
130β
131 await vi.advanceTimersByTimeAsync(10)
132β
133 const mutations = mutationCache.find({ mutationKey: ['bar'] })
134β
135 expect(mutations?.options.mutationKey).toEqual(['bar'])
136 })
137β
138 test('should update reactive options deeply', async () => {
139 type MutationKeyTest = {
140 entity: string
141 otherObject: {
142 name: string
143 }
144 }
145 const mutationKey = ref<Array<MutationKeyTest>>([
146 {
147 entity: 'test',
148 otherObject: { name: 'objectName' },
149 },
150 ])
151 const queryClient = useQueryClient()
152 const mutationCache = queryClient.getMutationCache()
153 const options = reactive({
154 mutationKey,
155 mutationFn: (params: string) => sleep(10).then(() => params),
156 })
157 const mutation = useMutation(options)
158β
159 mutationKey.value[0]!.otherObject.name = 'someOtherObjectName'
160 await vi.advanceTimersByTimeAsync(10)
161 mutation.mutate('xyz')
162β
163 await vi.advanceTimersByTimeAsync(10)
164β
165 const mutations = mutationCache.getAll()
166 const relevantMutation = mutations.find((m) => {
167 return (
168 Array.isArray(m.options.mutationKey) &&
169 !!m.options.mutationKey[0].otherObject
170 )
171 })
172β
173 expect(
174 (relevantMutation?.options.mutationKey as Array<MutationKeyTest>)[0]
175 ?.otherObject.name === 'someOtherObjectName',
176 ).toBe(true)
177 })
178β
179 test('should allow for non-options object (mutationFn or mutationKey) passed as arg1 & arg2 to trigger reactive updates', async () => {
180 const mutationKey = ref<Array<string>>(['foo2'])
181 const mutationFn = ref((params: string) => sleep(0).then(() => params))
182 const queryClient = useQueryClient()
183 const mutationCache = queryClient.getMutationCache()
184 const mutation = useMutation({ mutationKey, mutationFn })
185β
186 mutationKey.value = ['bar2']
187 let proof = false
188 mutationFn.value = (params: string) => {
189 proof = true
190 return sleep(10).then(() => params)
191 }
192 await vi.advanceTimersByTimeAsync(10)
193β
194 mutation.mutate('xyz')
195 await vi.advanceTimersByTimeAsync(10)
196β
197 const mutations = mutationCache.find({ mutationKey: ['bar2'] })
198 expect(mutations?.options.mutationKey).toEqual(['bar2'])
199 expect(proof).toEqual(true)
200 })
201β
202 test('should reset state after invoking mutation.reset', async () => {
203 const mutation = useMutation({
204 mutationFn: () =>
205 sleep(10).then(() => Promise.reject(new Error('Some error'))),
206 })
207β
208 mutation.mutate()
209β
210 await vi.advanceTimersByTimeAsync(10)
211β
212 mutation.reset()
213β
214 expect(mutation).toMatchObject({
215 isIdle: { value: true },
216 isPending: { value: false },
217 isError: { value: false },
218 isSuccess: { value: false },
219 data: { value: undefined },
220 error: { value: null },
221 })
222 })
223β
224 describe('side effects', () => {
225 beforeEach(() => {
226 vi.clearAllMocks()
227 })
228β
229 test('should call onMutate when passed as an option', async () => {
230 const onMutate = vi.fn()
231 const mutation = useMutation({
232 mutationFn: (params: string) => sleep(10).then(() => params),
233 onMutate,
234 })
235β
236 mutation.mutate('')
237β
238 await vi.advanceTimersByTimeAsync(10)
239β
240 expect(onMutate).toHaveBeenCalledTimes(1)
241 })
242β
243 test('should call onError when passed as an option', async () => {
244 const onError = vi.fn()
245 const mutation = useMutation({
246 mutationFn: () =>
247 sleep(10).then(() => Promise.reject(new Error('Some error'))),
248 onError,
249 })
250β
251 mutation.mutate('')
252β
253 await vi.advanceTimersByTimeAsync(10)
254β
255 expect(onError).toHaveBeenCalledTimes(1)
256 })
257β
258 test('should call onSuccess when passed as an option', async () => {
259 const onSuccess = vi.fn()
260 const mutation = useMutation({
261 mutationFn: (params: string) => sleep(10).then(() => params),
262 onSuccess,
263 })
264β
265 mutation.mutate('')
266β
267 await vi.advanceTimersByTimeAsync(10)
268β
269 expect(onSuccess).toHaveBeenCalledTimes(1)
270 })
271β
272 test('should call onSettled when passed as an option', async () => {
273 const onSettled = vi.fn()
274 const mutation = useMutation({
275 mutationFn: (params: string) => sleep(10).then(() => params),
276 onSettled,
277 })
278β
279 mutation.mutate('')
280β
281 await vi.advanceTimersByTimeAsync(10)
282β
283 expect(onSettled).toHaveBeenCalledTimes(1)
284 })
285β
286 test('should call onError when passed as an argument of mutate function', async () => {
287 const onError = vi.fn()
288 const mutation = useMutation({
289 mutationFn: () =>
290 sleep(10).then(() => Promise.reject(new Error('Some error'))),
291 })
292β
293 mutation.mutate(undefined, { onError })
294β
295 await vi.advanceTimersByTimeAsync(10)
296β
297 expect(onError).toHaveBeenCalledTimes(1)
298 })
299β
300 test('should call onSuccess when passed as an argument of mutate function', async () => {
301 const onSuccess = vi.fn()
302 const mutation = useMutation({
303 mutationFn: (params: string) => sleep(10).then(() => params),
304 })
305β
306 mutation.mutate('', { onSuccess })
307β
308 await vi.advanceTimersByTimeAsync(10)
309β
310 expect(onSuccess).toHaveBeenCalledTimes(1)
311 })
312β
313 test('should call onSettled when passed as an argument of mutate function', async () => {
314 const onSettled = vi.fn()
315 const mutation = useMutation({
316 mutationFn: (params: string) => sleep(10).then(() => params),
317 })
318β
319 mutation.mutate('', { onSettled })
320β
321 await vi.advanceTimersByTimeAsync(10)
322β
323 expect(onSettled).toHaveBeenCalledTimes(1)
324 })
325β
326 test('should fire both onSettled functions', async () => {
327 const onSettled = vi.fn()
328 const onSettledOnFunction = vi.fn()
329 const mutation = useMutation({
330 mutationFn: (params: string) => sleep(10).then(() => params),
331 onSettled,
332 })
333β
334 mutation.mutate('', { onSettled: onSettledOnFunction })
335β
336 await vi.advanceTimersByTimeAsync(10)
337β
338 expect(onSettled).toHaveBeenCalledTimes(1)
339 expect(onSettledOnFunction).toHaveBeenCalledTimes(1)
340 })
341 })
342β
343 describe('async', () => {
344 beforeEach(() => {
345 vi.clearAllMocks()
346 })
347β
348 test('should resolve properly', async () => {
349 const result = 'Mock data'
350 const mutation = useMutation({
351 mutationFn: (params: string) => sleep(10).then(() => params),
352 })
353β
354 await vi.waitFor(() =>
355 expect(mutation.mutateAsync(result)).resolves.toBe(result),
356 )
357β
358 expect(mutation).toMatchObject({
359 isIdle: { value: false },
360 isPending: { value: false },
361 isError: { value: false },
362 isSuccess: { value: true },
363 data: { value: 'Mock data' },
364 error: { value: null },
365 })
366 })
367β
368 test('should throw on error', async () => {
369 const mutation = useMutation({
370 mutationFn: () =>
371 sleep(10).then(() => Promise.reject(new Error('Some error'))),
372 })
373β
374 await vi.waitFor(() =>
375 expect(mutation.mutateAsync()).rejects.toThrowError('Some error'),
376 )
377β
378 expect(mutation).toMatchObject({
379 isIdle: { value: false },
380 isPending: { value: false },
381 isError: { value: true },
382 isSuccess: { value: false },
383 data: { value: undefined },
384 error: { value: Error('Some error') },
385 })
386 })
387 })
388β
389 test('should warn when used outside of setup function in development mode', () => {
390 vi.stubEnv('NODE_ENV', 'development')
391 const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
392β
393 try {
394 useMutation({
395 mutationFn: (params: string) => sleep(0).then(() => params),
396 })
397β
398 expect(warnSpy).toHaveBeenCalledWith(
399 'vue-query composable like "useQuery()" should only be used inside a "setup()" function or a running effect scope. They might otherwise lead to memory leaks.',
400 )
401 } finally {
402 warnSpy.mockRestore()
403 vi.unstubAllEnvs()
404 }
405 })
406β
407 describe('throwOnError', () => {
408 test('should evaluate throwOnError when mutation is expected to throw', async () => {
409 const err = new Error('Expected mock error. All is well!')
410 const boundaryFn = vi.fn()
411 const { mutate } = useMutation({
412 mutationFn: () => sleep(10).then(() => Promise.reject(err)),
413 throwOnError: boundaryFn,
414 })
415β
416 mutate()
417β
418 await vi.advanceTimersByTimeAsync(10)
419β
420 expect(boundaryFn).toHaveBeenCalledTimes(1)
421 expect(boundaryFn).toHaveBeenCalledWith(err)
422 })
423β
424 test('should throw from error watcher when throwOnError returns true', async () => {
425 const throwOnErrorFn = vi.fn().mockReturnValue(true)
426 const { mutate } = useMutation({
427 mutationFn: () =>
428 sleep(10).then(() => Promise.reject(new Error('Some error'))),
429 throwOnError: throwOnErrorFn,
430 })
431β
432 mutate()
433β
434 // Suppress the Unhandled Rejection caused by watcher throw in Vue 3
435 const rejectionHandler = () => {}
436 process.on('unhandledRejection', rejectionHandler)
437β
438 await vi.advanceTimersByTimeAsync(10)
439β
440 process.off('unhandledRejection', rejectionHandler)
441β
442 expect(throwOnErrorFn).toHaveBeenCalledTimes(1)
443 expect(throwOnErrorFn).toHaveBeenCalledWith(Error('Some error'))
444 })
445 })
446})