'Handling the api error part in jest React testing library
I have the following function on form submit. There is no much form validations added for now and i make the post api call and submits the form on clicking save button. I have successfully wrote the test case for the successful form submission and not very sure how to go about the error scenario to cover the .catch((e) => {} part in general when the api fails.
const onSubmit: SubmitHandler<DoctorSettings> = (data) => {
userUpdateService
.updateUser(data)
.then((resp) => {
UtilsService.popUp("Successfully submitted form", "success");
})
.catch((e) => {
UtilsService.popUp("Error submitting form", "error");
});
};
I wrote the following test case for the successful form submit
const updateUser = jest.fn(() => Promise.resolve());
jest.mock("../services/userUpdateService.service", () => {
return function() {
return {
updateUser: updateUser,
};
};
});
test("should successfully submit the form when save is clciked", async () => {
const { findByTestId, getByTestId } = render(props);
const gender = await getByTestId(
"gender-select"
).querySelector('input[type="radio"]');
// ----------------
// ----------------
// ----------------
const saveButton = await findByTestId("save-button");
expect(gender).toBeInTheDocument();
// ----------------
// ----------------
// ----------------
expect(saveButton).toBeInTheDocument();
await act(async () => {
fireEvent.click(saveButton);
});
expect(updateUser).toBeCalled();
});
Solution 1:[1]
You should mock HTTP requests with tools like nock After mocking HTTP requests you can trigger an HTTP error with nock. You also should spyOn UtilsService.popup and test it called with correct values.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Can Küçüky?lmaz |
