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

useMutation.test.js

91 lines2.1 KB

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})