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

useMutation.test.tsx

479 lines11.9 KB

1import { fireEvent, waitFor } from '@testing-library/react'
2import React from 'react'
3​
4import { useMutation, QueryClient, QueryCache, MutationCache } from '../..'
5import { UseMutationResult } from '../types'
6import {
7 mockConsoleError,
8 mockNavigatorOnLine,
9 queryKey,
10 renderWithClient,
11 setActTimeout,
12 sleep,
13} from './utils'
14​
15describe('useMutation', () => {
16 const queryCache = new QueryCache()
17 const mutationCache = new MutationCache()
18 const queryClient = new QueryClient({ queryCache, mutationCache })
19​
20 it('should be able to reset `data`', async () => {
21 function Page() {
22 const { mutate, data = '', reset } = useMutation(() =>
23 Promise.resolve('mutation')
24 )
25​
26 return (
27 <div>
28 <h1 data-testid="title">{data}</h1>
29 <button onClick={() => reset()}>reset</button>
30 <button onClick={() => mutate()}>mutate</button>
31 </div>
32 )
33 }
34​
35 const { getByTestId, getByText } = renderWithClient(queryClient, <Page />)
36​
37 expect(getByTestId('title').textContent).toBe('')
38​
39 fireEvent.click(getByText('mutate'))
40​
41 await waitFor(() => getByTestId('title'))
42​
43 expect(getByTestId('title').textContent).toBe('mutation')
44​
45 fireEvent.click(getByText('reset'))
46​
47 await waitFor(() => getByTestId('title'))
48​
49 expect(getByTestId('title').textContent).toBe('')
50 })
51​
52 it('should be able to reset `error`', async () => {
53 const consoleMock = mockConsoleError()
54​
55 function Page() {
56 const { mutate, error, reset } = useMutation<string, Error>(() => {
57 const err = new Error('Expected mock error. All is well!')
58 err.stack = ''
59 return Promise.reject(err)
60 })
61​
62 return (
63 <div>
64 {error && <h1 data-testid="error">{error.message}</h1>}
65 <button onClick={() => reset()}>reset</button>
66 <button onClick={() => mutate()}>mutate</button>
67 </div>
68 )
69 }
70​
71 const { getByTestId, getByText, queryByTestId } = renderWithClient(
72 queryClient,
73 <Page />
74 )
75​
76 expect(queryByTestId('error')).toBeNull()
77​
78 fireEvent.click(getByText('mutate'))
79​
80 await waitFor(() => getByTestId('error'))
81​
82 expect(getByTestId('error').textContent).toBe(
83 'Expected mock error. All is well!'
84 )
85​
86 fireEvent.click(getByText('reset'))
87​
88 await waitFor(() => expect(queryByTestId('error')).toBeNull())
89​
90 consoleMock.mockRestore()
91 })
92​
93 it('should be able to call `onSuccess` and `onSettled` after each successful mutate', async () => {
94 let count = 0
95 const onSuccessMock = jest.fn()
96 const onSettledMock = jest.fn()
97​
98 function Page() {
99 const { mutate } = useMutation(
100 async (vars: { count: number }) => Promise.resolve(vars.count),
101 {
102 onSuccess: data => {
103 onSuccessMock(data)
104 },
105 onSettled: data => {
106 onSettledMock(data)
107 },
108 }
109 )
110​
111 return (
112 <div>
113 <h1 data-testid="title">{count}</h1>
114 <button onClick={() => mutate({ count: ++count })}>mutate</button>
115 </div>
116 )
117 }
118​
119 const { getByTestId, getByText } = renderWithClient(queryClient, <Page />)
120​
121 expect(getByTestId('title').textContent).toBe('0')
122​
123 fireEvent.click(getByText('mutate'))
124 fireEvent.click(getByText('mutate'))
125 fireEvent.click(getByText('mutate'))
126​
127 await waitFor(() => getByTestId('title'))
128​
129 expect(onSuccessMock).toHaveBeenCalledTimes(3)
130 expect(onSuccessMock).toHaveBeenCalledWith(1)
131 expect(onSuccessMock).toHaveBeenCalledWith(2)
132 expect(onSuccessMock).toHaveBeenCalledWith(3)
133​
134 expect(onSettledMock).toHaveBeenCalledTimes(3)
135 expect(onSettledMock).toHaveBeenCalledWith(1)
136 expect(onSettledMock).toHaveBeenCalledWith(2)
137 expect(onSettledMock).toHaveBeenCalledWith(3)
138​
139 expect(getByTestId('title').textContent).toBe('3')
140 })
141​
142 it('should be able to call `onError` and `onSettled` after each failed mutate', async () => {
143 const consoleMock = mockConsoleError()
144​
145 const onErrorMock = jest.fn()
146 const onSettledMock = jest.fn()
147 let count = 0
148​
149 function Page() {
150 const { mutate } = useMutation(
151 (vars: { count: number }) => {
152 const error = new Error(
153 `Expected mock error. All is well! ${vars.count}`
154 )
155 error.stack = ''
156 return Promise.reject(error)
157 },
158 {
159 onError: (error: Error) => {
160 onErrorMock(error.message)
161 },
162 onSettled: (_data, error) => {
163 onSettledMock(error?.message)
164 },
165 }
166 )
167​
168 return (
169 <div>
170 <h1 data-testid="title">{count}</h1>
171 <button onClick={() => mutate({ count: ++count })}>mutate</button>
172 </div>
173 )
174 }
175​
176 const { getByTestId, getByText } = renderWithClient(queryClient, <Page />)
177​
178 expect(getByTestId('title').textContent).toBe('0')
179​
180 fireEvent.click(getByText('mutate'))
181 fireEvent.click(getByText('mutate'))
182 fireEvent.click(getByText('mutate'))
183​
184 await waitFor(() => getByTestId('title'))
185​
186 expect(onErrorMock).toHaveBeenCalledTimes(3)
187 expect(onErrorMock).toHaveBeenCalledWith(
188 'Expected mock error. All is well! 1'
189 )
190 expect(onErrorMock).toHaveBeenCalledWith(
191 'Expected mock error. All is well! 2'
192 )
193 expect(onErrorMock).toHaveBeenCalledWith(
194 'Expected mock error. All is well! 3'
195 )
196​
197 expect(onSettledMock).toHaveBeenCalledTimes(3)
198 expect(onSettledMock).toHaveBeenCalledWith(
199 'Expected mock error. All is well! 1'
200 )
201 expect(onSettledMock).toHaveBeenCalledWith(
202 'Expected mock error. All is well! 2'
203 )
204 expect(onSettledMock).toHaveBeenCalledWith(
205 'Expected mock error. All is well! 3'
206 )
207​
208 expect(getByTestId('title').textContent).toBe('3')
209​
210 consoleMock.mockRestore()
211 })
212​
213 it('should be able to override the useMutation success callbacks', async () => {
214 const callbacks: string[] = []
215​
216 function Page() {
217 const { mutateAsync } = useMutation(async (text: string) => text, {
218 onSuccess: async () => {
219 callbacks.push('useMutation.onSuccess')
220 },
221 onSettled: async () => {
222 callbacks.push('useMutation.onSettled')
223 },
224 })
225​
226 React.useEffect(() => {
227 setActTimeout(async () => {
228 try {
229 const result = await mutateAsync('todo', {
230 onSuccess: async () => {
231 callbacks.push('mutateAsync.onSuccess')
232 },
233 onSettled: async () => {
234 callbacks.push('mutateAsync.onSettled')
235 },
236 })
237 callbacks.push(`mutateAsync.result:${result}`)
238 } catch {}
239 }, 10)
240 }, [mutateAsync])
241​
242 return null
243 }
244​
245 renderWithClient(queryClient, <Page />)
246​
247 await sleep(100)
248​
249 expect(callbacks).toEqual([
250 'useMutation.onSuccess',
251 'useMutation.onSettled',
252 'mutateAsync.onSuccess',
253 'mutateAsync.onSettled',
254 'mutateAsync.result:todo',
255 ])
256 })
257​
258 it('should be able to override the error callbacks when using mutateAsync', async () => {
259 const consoleMock = mockConsoleError()
260​
261 const callbacks: string[] = []
262​
263 function Page() {
264 const { mutateAsync } = useMutation(
265 async (_text: string) => Promise.reject('oops'),
266 {
267 onError: async () => {
268 callbacks.push('useMutation.onError')
269 },
270 onSettled: async () => {
271 callbacks.push('useMutation.onSettled')
272 },
273 }
274 )
275​
276 React.useEffect(() => {
277 setActTimeout(async () => {
278 try {
279 await mutateAsync('todo', {
280 onError: async () => {
281 callbacks.push('mutateAsync.onError')
282 },
283 onSettled: async () => {
284 callbacks.push('mutateAsync.onSettled')
285 },
286 })
287 } catch (error) {
288 callbacks.push(`mutateAsync.error:${error}`)
289 }
290 }, 10)
291 }, [mutateAsync])
292​
293 return null
294 }
295​
296 renderWithClient(queryClient, <Page />)
297​
298 await sleep(100)
299​
300 expect(callbacks).toEqual([
301 'useMutation.onError',
302 'useMutation.onSettled',
303 'mutateAsync.onError',
304 'mutateAsync.onSettled',
305 'mutateAsync.error:oops',
306 ])
307​
308 consoleMock.mockRestore()
309 })
310​
311 it('should be able to use mutation defaults', async () => {
312 const key = queryKey()
313​
314 queryClient.setMutationDefaults(key, {
315 mutationFn: async (text: string) => text,
316 })
317​
318 const states: UseMutationResult<any, any, any, any>[] = []
319​
320 function Page() {
321 const state = useMutation<string, unknown, string>(key)
322​
323 states.push(state)
324​
325 const { mutate } = state
326​
327 React.useEffect(() => {
328 setActTimeout(() => {
329 mutate('todo')
330 }, 10)
331 }, [mutate])
332​
333 return null
334 }
335​
336 renderWithClient(queryClient, <Page />)
337​
338 await sleep(100)
339​
340 expect(states.length).toBe(3)
341 expect(states[0]).toMatchObject({ data: undefined, isLoading: false })
342 expect(states[1]).toMatchObject({ data: undefined, isLoading: true })
343 expect(states[2]).toMatchObject({ data: 'todo', isLoading: false })
344 })
345​
346 it('should be able to retry a failed mutation', async () => {
347 const consoleMock = mockConsoleError()
348​
349 let count = 0
350​
351 function Page() {
352 const { mutate } = useMutation(
353 (_text: string) => {
354 count++
355 return Promise.reject('oops')
356 },
357 {
358 retry: 1,
359 retryDelay: 5,
360 }
361 )
362​
363 React.useEffect(() => {
364 setActTimeout(() => {
365 mutate('todo')
366 }, 10)
367 }, [mutate])
368​
369 return null
370 }
371​
372 renderWithClient(queryClient, <Page />)
373​
374 await sleep(100)
375​
376 expect(count).toBe(2)
377​
378 consoleMock.mockRestore()
379 })
380​
381 it('should be able to retry a mutation when online', async () => {
382 const consoleMock = mockConsoleError()
383 mockNavigatorOnLine(false)
384​
385 let count = 0
386 const states: UseMutationResult<any, any, any, any>[] = []
387​
388 function Page() {
389 const state = useMutation(
390 (_text: string) => {
391 count++
392 return count > 1 ? Promise.resolve('data') : Promise.reject('oops')
393 },
394 {
395 retry: 1,
396 retryDelay: 5,
397 }
398 )
399​
400 states.push(state)
401​
402 const { mutate } = state
403​
404 React.useEffect(() => {
405 setActTimeout(() => {
406 mutate('todo')
407 }, 10)
408 }, [mutate])
409​
410 return null
411 }
412​
413 renderWithClient(queryClient, <Page />)
414​
415 await sleep(50)
416​
417 expect(states.length).toBe(4)
418 expect(states[0]).toMatchObject({
419 isLoading: false,
420 isPaused: false,
421 failureCount: 0,
422 })
423 expect(states[1]).toMatchObject({
424 isLoading: true,
425 isPaused: false,
426 failureCount: 0,
427 })
428 expect(states[2]).toMatchObject({
429 isLoading: true,
430 isPaused: false,
431 failureCount: 1,
432 })
433 expect(states[3]).toMatchObject({
434 isLoading: true,
435 isPaused: true,
436 failureCount: 1,
437 })
438​
439 mockNavigatorOnLine(true)
440 window.dispatchEvent(new Event('online'))
441​
442 await sleep(50)
443​
444 expect(states.length).toBe(6)
445 expect(states[4]).toMatchObject({
446 isLoading: true,
447 isPaused: false,
448 failureCount: 1,
449 })
450 expect(states[5]).toMatchObject({
451 isLoading: false,
452 isPaused: false,
453 failureCount: 1,
454 data: 'data',
455 })
456​
457 consoleMock.mockRestore()
458 })
459​
460 it('should not change state if unmounted', async () => {
461 function Mutates() {
462 const { mutate } = useMutation(() => sleep(10))
463 return <button onClick={() => mutate()}>mutate</button>
464 }
465 function Page() {
466 const [mounted, setMounted] = React.useState(true)
467 return (
468 <div>
469 <button onClick={() => setMounted(false)}>unmount</button>
470 {mounted && <Mutates />}
471 </div>
472 )
473 }
474​
475 const { getByText } = renderWithClient(queryClient, <Page />)
476 fireEvent.click(getByText('mutate'))
477 fireEvent.click(getByText('unmount'))
478 })
479})