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

useMutation.test.ts

373 lines10.3 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 update reactive options', async () => {
86 const queryClient = useQueryClient()
87 const mutationCache = queryClient.getMutationCache()
88 const options = reactive({
89 mutationKey: ['foo'],
90 mutationFn: (params: string) => sleep(10).then(() => params),
91 })
92 const mutation = useMutation(options)
93​
94 options.mutationKey = ['bar']
95 await vi.advanceTimersByTimeAsync(10)
96 mutation.mutate('xyz')
97​
98 await vi.advanceTimersByTimeAsync(10)
99​
100 const mutations = mutationCache.find({ mutationKey: ['bar'] })
101​
102 expect(mutations?.options.mutationKey).toEqual(['bar'])
103 })
104​
105 test('should update reactive options deeply', async () => {
106 type MutationKeyTest = {
107 entity: string
108 otherObject: {
109 name: string
110 }
111 }
112 const mutationKey = ref<Array<MutationKeyTest>>([
113 {
114 entity: 'test',
115 otherObject: { name: 'objectName' },
116 },
117 ])
118 const queryClient = useQueryClient()
119 const mutationCache = queryClient.getMutationCache()
120 const options = reactive({
121 mutationKey,
122 mutationFn: (params: string) => sleep(10).then(() => params),
123 })
124 const mutation = useMutation(options)
125​
126 mutationKey.value[0]!.otherObject.name = 'someOtherObjectName'
127 await vi.advanceTimersByTimeAsync(10)
128 mutation.mutate('xyz')
129​
130 await vi.advanceTimersByTimeAsync(10)
131​
132 const mutations = mutationCache.getAll()
133 const relevantMutation = mutations.find((m) => {
134 return (
135 Array.isArray(m.options.mutationKey) &&
136 !!m.options.mutationKey[0].otherObject
137 )
138 })
139​
140 expect(
141 (relevantMutation?.options.mutationKey as Array<MutationKeyTest>)[0]
142 ?.otherObject.name === 'someOtherObjectName',
143 ).toBe(true)
144 })
145​
146 test('should allow for non-options object (mutationFn or mutationKey) passed as arg1 & arg2 to trigger reactive updates', async () => {
147 const mutationKey = ref<Array<string>>(['foo2'])
148 const mutationFn = ref((params: string) => sleep(0).then(() => params))
149 const queryClient = useQueryClient()
150 const mutationCache = queryClient.getMutationCache()
151 const mutation = useMutation({ mutationKey, mutationFn })
152​
153 mutationKey.value = ['bar2']
154 let proof = false
155 mutationFn.value = (params: string) => {
156 proof = true
157 return sleep(10).then(() => params)
158 }
159 await vi.advanceTimersByTimeAsync(10)
160​
161 mutation.mutate('xyz')
162 await vi.advanceTimersByTimeAsync(10)
163​
164 const mutations = mutationCache.find({ mutationKey: ['bar2'] })
165 expect(mutations?.options.mutationKey).toEqual(['bar2'])
166 expect(proof).toEqual(true)
167 })
168​
169 test('should reset state after invoking mutation.reset', async () => {
170 const mutation = useMutation({
171 mutationFn: () =>
172 sleep(10).then(() => Promise.reject(new Error('Some error'))),
173 })
174​
175 mutation.mutate()
176​
177 await vi.advanceTimersByTimeAsync(10)
178​
179 mutation.reset()
180​
181 expect(mutation).toMatchObject({
182 isIdle: { value: true },
183 isPending: { value: false },
184 isError: { value: false },
185 isSuccess: { value: false },
186 data: { value: undefined },
187 error: { value: null },
188 })
189 })
190​
191 describe('side effects', () => {
192 beforeEach(() => {
193 vi.clearAllMocks()
194 })
195​
196 test('should call onMutate when passed as an option', async () => {
197 const onMutate = vi.fn()
198 const mutation = useMutation({
199 mutationFn: (params: string) => sleep(10).then(() => params),
200 onMutate,
201 })
202​
203 mutation.mutate('')
204​
205 await vi.advanceTimersByTimeAsync(10)
206​
207 expect(onMutate).toHaveBeenCalledTimes(1)
208 })
209​
210 test('should call onError when passed as an option', async () => {
211 const onError = vi.fn()
212 const mutation = useMutation({
213 mutationFn: () =>
214 sleep(10).then(() => Promise.reject(new Error('Some error'))),
215 onError,
216 })
217​
218 mutation.mutate('')
219​
220 await vi.advanceTimersByTimeAsync(10)
221​
222 expect(onError).toHaveBeenCalledTimes(1)
223 })
224​
225 test('should call onSuccess when passed as an option', async () => {
226 const onSuccess = vi.fn()
227 const mutation = useMutation({
228 mutationFn: (params: string) => sleep(10).then(() => params),
229 onSuccess,
230 })
231​
232 mutation.mutate('')
233​
234 await vi.advanceTimersByTimeAsync(10)
235​
236 expect(onSuccess).toHaveBeenCalledTimes(1)
237 })
238​
239 test('should call onSettled when passed as an option', async () => {
240 const onSettled = vi.fn()
241 const mutation = useMutation({
242 mutationFn: (params: string) => sleep(10).then(() => params),
243 onSettled,
244 })
245​
246 mutation.mutate('')
247​
248 await vi.advanceTimersByTimeAsync(10)
249​
250 expect(onSettled).toHaveBeenCalledTimes(1)
251 })
252​
253 test('should call onError when passed as an argument of mutate function', async () => {
254 const onError = vi.fn()
255 const mutation = useMutation({
256 mutationFn: () =>
257 sleep(10).then(() => Promise.reject(new Error('Some error'))),
258 })
259​
260 mutation.mutate(undefined, { onError })
261​
262 await vi.advanceTimersByTimeAsync(10)
263​
264 expect(onError).toHaveBeenCalledTimes(1)
265 })
266​
267 test('should call onSuccess when passed as an argument of mutate function', async () => {
268 const onSuccess = vi.fn()
269 const mutation = useMutation({
270 mutationFn: (params: string) => sleep(10).then(() => params),
271 })
272​
273 mutation.mutate('', { onSuccess })
274​
275 await vi.advanceTimersByTimeAsync(10)
276​
277 expect(onSuccess).toHaveBeenCalledTimes(1)
278 })
279​
280 test('should call onSettled when passed as an argument of mutate function', async () => {
281 const onSettled = vi.fn()
282 const mutation = useMutation({
283 mutationFn: (params: string) => sleep(10).then(() => params),
284 })
285​
286 mutation.mutate('', { onSettled })
287​
288 await vi.advanceTimersByTimeAsync(10)
289​
290 expect(onSettled).toHaveBeenCalledTimes(1)
291 })
292​
293 test('should fire both onSettled functions', async () => {
294 const onSettled = vi.fn()
295 const onSettledOnFunction = vi.fn()
296 const mutation = useMutation({
297 mutationFn: (params: string) => sleep(10).then(() => params),
298 onSettled,
299 })
300​
301 mutation.mutate('', { onSettled: onSettledOnFunction })
302​
303 await vi.advanceTimersByTimeAsync(10)
304​
305 expect(onSettled).toHaveBeenCalledTimes(1)
306 expect(onSettledOnFunction).toHaveBeenCalledTimes(1)
307 })
308 })
309​
310 describe('async', () => {
311 beforeEach(() => {
312 vi.clearAllMocks()
313 })
314​
315 test('should resolve properly', async () => {
316 const result = 'Mock data'
317 const mutation = useMutation({
318 mutationFn: (params: string) => sleep(10).then(() => params),
319 })
320​
321 await vi.waitFor(() =>
322 expect(mutation.mutateAsync(result)).resolves.toBe(result),
323 )
324​
325 expect(mutation).toMatchObject({
326 isIdle: { value: false },
327 isPending: { value: false },
328 isError: { value: false },
329 isSuccess: { value: true },
330 data: { value: 'Mock data' },
331 error: { value: null },
332 })
333 })
334​
335 test('should throw on error', async () => {
336 const mutation = useMutation({
337 mutationFn: () =>
338 sleep(10).then(() => Promise.reject(new Error('Some error'))),
339 })
340​
341 await vi.waitFor(() =>
342 expect(mutation.mutateAsync()).rejects.toThrowError('Some error'),
343 )
344​
345 expect(mutation).toMatchObject({
346 isIdle: { value: false },
347 isPending: { value: false },
348 isError: { value: true },
349 isSuccess: { value: false },
350 data: { value: undefined },
351 error: { value: Error('Some error') },
352 })
353 })
354 })
355​
356 describe('throwOnError', () => {
357 test('should evaluate throwOnError when mutation is expected to throw', async () => {
358 const err = new Error('Expected mock error. All is well!')
359 const boundaryFn = vi.fn()
360 const { mutate } = useMutation({
361 mutationFn: () => sleep(10).then(() => Promise.reject(err)),
362 throwOnError: boundaryFn,
363 })
364​
365 mutate()
366​
367 await vi.advanceTimersByTimeAsync(10)
368​
369 expect(boundaryFn).toHaveBeenCalledTimes(1)
370 expect(boundaryFn).toHaveBeenCalledWith(err)
371 })
372 })
373})