I've got a basic component which submits a form. This is the segments where the form submission is declared:
<form id="register" onSubmit={handleSubmit(onSubmit)}>
and the function that handles the data is:
const onSubmit = async data => {
const res = await axios.post("http://localhost", data)
.then( (response) => {
console.log(response);
})
.catch(error => {
console.log(error);
});
}
In my test I've declared the mock and the test looks like:
import axios from "axios";
jest.mock('axios', () => {
post: () => Promise.resolve({data: []})
})
it('should save value when submitted', async () => {
render(
<Register />
);
ReactTestUtils.Simulate.change(field('email'), {
target: { value: 'test@mail.com', name: 'email'}
})
ReactTestUtils.Simulate.change(field('first-name'), {
target: { value: 'test', name: 'first-name'}
})
ReactTestUtils.Simulate.change(field('last-name'), {
target: { value: 'test', name: 'last-name'}
})
ReactTestUtils.Simulate.change(field('password'), {
target: { value: 'test', name: 'password'}
})
ReactTestUtils.Simulate.change(field('confirm-password'), {
target: { value: 'test', name: 'confirm-password'}
})
ReactTestUtils.Simulate.submit(form('register'));
expect(axios.post).toHaveBeenCalledTimes(1);
});
Note: field
and form
are simply helpers that get me any field and the form. They work fine, they've been used in other tests.
After running the test I'm getting the following error:
RUNS test/Register.test.js node:internal/process/promises:245 triggerUncaughtException(err, true /* fromPromise */); ^
[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "TypeError: Cannot read property 'post' of undefined".] {
code: 'ERR_UNHANDLED_REJECTION' }
What's going on here? am I not handling the rejection in the catch
statement?