Open History to see the last commit
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})