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