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

useMutation.test.ts

355 lines9.6 KB

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