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

useMutation.test.ts

406 lines11.2 KB

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 describe('throwOnError', () => {
390 test('should evaluate throwOnError when mutation is expected to throw', async () => {
391 const err = new Error('Expected mock error. All is well!')
392 const boundaryFn = vi.fn()
393 const { mutate } = useMutation({
394 mutationFn: () => sleep(10).then(() => Promise.reject(err)),
395 throwOnError: boundaryFn,
396 })
397​
398 mutate()
399​
400 await vi.advanceTimersByTimeAsync(10)
401​
402 expect(boundaryFn).toHaveBeenCalledTimes(1)
403 expect(boundaryFn).toHaveBeenCalledWith(err)
404 })
405 })
406})