How I can test in jest error case? This is what I do: I don't know if exist a method how to test this.
it ('the fetch fails and throw an error', async () => {
let response = {
status: 400,
body:
{
base : "RON",
date: "2019-08-01",
rates: {"error": 'error'}
}
};
fetch.mockReject(response)
try {
await fetchData();
} catch (e) {
expect(e).toEqual(response);
expect(await fetchData()).rejects.toThrow(e);
}
});
This is the code:
fetchData = async () => {
try {
const response = await fetch('https://api.exo/latest?base=RON');
const data = await response.json();
return data;
} catch (e) {
throw e;
}
};
You can do it in the following way:
Read more docs.
expect.assertions to the rescue
Test will fail once no exception is thrown. It has advantages over
expect().toThrown
:it()
to make it workexpect(e).toMatchObject({})
to skip some data you don't care about in current test case)As for disadvantages - you have to update number manually after adding new assertions