Open History to see the last commit
1import {
2 cleanup,
3 render,
4 fireEvent,
5 waitFor,
6} from '@testing-library/react'
7import * as React from 'react'
8β
9import { useMutation } from '../index'
10β
11describe('useMutation', () => {
12 afterEach(cleanup)
13β
14 it('should be able to reset `data`', async () => {
15 function Page() {
16 const [mutate, { data = '', reset }] = useMutation(() =>
17 Promise.resolve('mutation')
18 )
19β
20 return (
21 <div>
22 <h1 data-testid="title">{data}</h1>
23 <button onClick={reset}>reset</button>
24 <button onClick={mutate}>mutate</button>
25 </div>
26 )
27 }
28β
29 const { getByTestId, getByText } = render(<Page />)
30β
31 expect(getByTestId('title').textContent).toBe('')
32β
33 fireEvent.click(getByText('mutate'))
34β
35 await waitFor(() => getByTestId('title'))
36β
37 expect(getByTestId('title').textContent).toBe('mutation')
38β
39 fireEvent.click(getByText('reset'))
40β
41 await waitFor(() => getByTestId('title'))
42β
43 expect(getByTestId('title').textContent).toBe('')
44 })
45β
46 it('should be able to reset `error`', async () => {
47 jest.spyOn(console, 'error')
48 console.error.mockImplementation(() => {})
49β
50 function Page() {
51 const [mutate, mutationResult] = useMutation(
52 () => {
53 const error = new Error('Expected mock error. All is well!')
54 error.stack = ''
55 return Promise.reject(error)
56 },
57 {
58 throwOnError: false,
59 }
60 )
61β
62 return (
63 <div>
64 {mutationResult.error && (
65 <h1 data-testid="error">{mutationResult.error.message}</h1>
66 )}
67 <button onClick={mutationResult.reset}>reset</button>
68 <button onClick={mutate}>mutate</button>
69 </div>
70 )
71 }
72β
73 const { getByTestId, getByText, queryByTestId } = render(<Page />)
74β
75 expect(queryByTestId('error')).toBeNull()
76β
77 fireEvent.click(getByText('mutate'))
78β
79 await waitFor(() => getByTestId('error'))
80β
81 expect(getByTestId('error').textContent).toBe(
82 'Expected mock error. All is well!'
83 )
84β
85 fireEvent.click(getByText('reset'))
86β
87 expect(queryByTestId('error')).toBeNull()
88β
89 console.error.mockRestore()
90 })
91})