2

How to write test cases using React Testing Library for useMutation which covers the onError and onSuccess callbacks.

const useSubmitform = () =>{
    const {mutate}  = useMutation((payload)=>{
       //axios call
    },
    { 
        onError: (error)=>{
            console.log(error);
        },
        onSuccess: (data)=>{
            console.log(data);
        },
    });
  return mutate;
}
7
  • Where does the useMutation hook come from? Commented Nov 3, 2021 at 2:43
  • imported from react-query Commented Nov 3, 2021 at 4:46
  • 1
    Can you show the code of axios call? Commented Nov 3, 2021 at 5:29
  • I was confused, React Testing Library builds on top of dom test, how do you use it to test an individual mutation without rendered component. Commented Nov 3, 2021 at 6:57
  • The use case is, onclick of button useSubmitform is called. if the axios call returns {status : 400/500} error then onError Is invoked , for { status: 200} onSuccess is invoked Commented Nov 3, 2021 at 7:33

1 Answer 1

3

React Testing Library builds on dom test. To use it test mutation callback, you need render the callback status in component.

function TestComponent() {
  const mutation = useSubmitform()
  return (
    <div>
      <button onClick={submit}>{ mutation.isLoading ? 'Loading' : 'Submit' }</button>
      { mutation.isError && <p role="alert">failed</p> }
      { mutation.isSuccess && <p role="alert">success</p> }
    </div>
  )
}
test('test a test exam', () => {
  render(<TestComponent />)
  fireEvent.click(screen.getByText('Submit'))
  waitFor(() => screen.getByRole('alert'))
  expect(screen.getByRole('alert')).toHaveTextContent('success')
})

The above code can test mutation results, in addition you can use msw to mock http request:

function TestComponent() {
  const mutation = useSubmitform()
  return (
    <div>
      <button onClick={submit}>Submit</button>
      { mutation.isError && <p role="alert">failed</p> }
      { mutation.isSuccess && <p role="alert">success</p> }
    </div>
  )
}
const server = setupServer(
  rest.get('/axios/api', (req, res, ctx) => {
    return res(ctx.json({message: 'mock server'}))
  }),
)

beforeAll(() => server.listen())
afterEach(() => server.resetHandlers())
afterAll(() => server.close())

test('test failed', () => {
  server.use(
    // Mock api
    rest.post('/axios/api', (req, res, ctx) => {
      return res(
        ctx.status(500),
        ctx.json({ message: 'Error' }),
      )
    })
  )
  render(<TestComponent />)
  fireEvent.click(screen.getByText('Submit'))
  await waitFor(() => screen.getByRole('alert'))
  expect(screen.getByRole('alert')).toHaveTextContent('failed')
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.