Assuming that I have the following function, in which I want to handle different axios erroneous responses in different ways.
async fetchData() {
const data = {...};
const response = await axios.post('endpoint_here', data)
.catch((error) => {
if (error.code === SomeKindOfError) {
throw new SomeKindOfError(error.message);
}
if (error.code === AnotherKindOfError) {
throw new AnotherKindOfError(error.message);
}
throw new Error(error.message);
});
return response.data;
}
How can I test all these different cases in my test using Jest?
At the moment my test is this:
test('test SomeKindOfError', async () => {
axios.post.mockRejectedValueOnce(new SomeKindOfError('There was an error.'));
await expect(fetchData())
.rejects
.toThrowError(new SomeKindOfError('There was an error.'));
});
The above test is a pass, but it is nothing close to what a proper test for this function should be.
I would want to be able to check what the error returned from Axios is, and accordingly test that my own custom made errors get thrown.
Ideally, a way of mocking the Axios error response that will allow me to cover all the different cases in my tests, something like the following:
test('test SomeKindOfError', async () => {
axios.post.mockImplementation(() => Promise.reject({
error: { code: SomeKindOfError.code },
}));
await expect(fetchData())
.rejects
.toThrowError(new SomeKindOfError('There was an error.'));
});
Eventually, the solution was as simple as this:
test('test SomeKindOfError', async () => {
axios.post.mockRejectedValueOnce({ code: SomeKindOfError });
await expect(fetchData())
.rejects
.toThrowError(new SomeKindOfError('There was an error.'));
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.