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

useMutation.test.tsx

586 lines14.6 KB

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