I have an axios code that calls an endpoint which returns 302 and a Location: header. I am writing a test which should evaluate method response and confirm the correct (HTTP 302) response as well as check Location: URL contents.
So I have a test code (Jest)
let axiosReply = await axios.get(this.redirectUrl, {
maxRedirects: 0 // do not follow redirects...
});
expect(axiosReply.status).toBe(302);
// some checks of header Location: follow
however, axios throws an error:
Error: Request failed with status code 302
at createError (C:\<my project folder>\node_modules\axios\lib\core\createError.js:16:15)
at settle (C:\<my project folder>\node_modules\axios\lib\core\settle.js:17:12)
at IncomingMessage.handleStreamEnd (C:\<my project folder>\node_modules\axios\lib\adapters\http.js:260:11)
at IncomingMessage.emit (events.js:215:7)
at endReadableNT (_stream_readable.js:1184:12)
at processTicksAndRejections (internal/process/task_queues.js:80:21)
How can I configure Axios just to return the reply and do not throw an error?
In order not to throw, use valudateStatus option:
result = await axios.get(this.url, {
validateStatus: function (status) {
// if this function returns true, exception is not thrown, so
// in simplest case just return true to handle status checks externally.
return true;
}
});
if (result.status === StatusCodes.FORBIDDEN) {
// react on a 403 error in a custom way
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With