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')
})
useMutationhook come from?react-query