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

useMutation.test.ts

364 lines9.7 KB

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