[英]Testing 400 status code axios throws error
我正在為一個正在研究的項目創建一個api測試框架,並且希望驗證要發送到端點的JSON對象中的必填字段。
我正在嘗試發送帶有缺少字段的JSON對象,並期望來自我的應用程序的400響應以及驗證消息。 但是,當使用axios進行此調用時(一定正確),它在收到400時會引發錯誤。
我希望能夠斷言期望是400並在驗證消息中斷言。
我遇到的所有示例都是關於以正確的方式處理400響應,如果您不期望400響應,但是我期望這樣。
我似乎找不到其他嘗試此方法的人。
async function createReminder(reminderObject) {
const response = await axios.post(`${config.get('baseUrl')}/reminder`, {
...reminderObject
});
return response;
}
module.exports.createReminder = createReminder;
這是我目前的工作代碼。 與有效的呼叫一起使用時,這將產生有效的200。
我需要在響應對象中返回400響應/驗證消息,以在調用此函數的函數中進行處理。
實際上,您想攔截響應並根據需要對其進行轉換。 axios文檔中有專門針對攔截器的部分 。 作為您可以使用它的示例,這是我最近在一個帶有Laravel后端的項目中使用的方法:
axios.interceptors.response.use(
res => Promise.resolve(res.data),
error => {
let message = null;
if (error.response) {
// if error has a data.error property, it's an error formatted by server
if (error.response.data.error) message = error.response.data.error;
else if (error.response.status === 500) message = 'Oops! Something went wrong.';
} else {
// if error has a code property, it's an error defined by axios
if (error.code === 'ECONNABORTED') message = 'Timeout exceeded';
else message = 'Oops! Something went wrong.';
}
// eslint-disable-next-line prefer-promise-reject-errors
return Promise.reject({ error: message });
}
);
上面的代碼使我可以如下進行axios調用,並且始終期望使用相同的格式:
axios.post('/url', { data: { ... }})
.then(({ jsonProp1 }) => console.log(jsonProp1))
.catch(({ error }) => console.log(error);
注意:如果確實創建了新的axios實例,則也需要為此實例重新注入響應攔截器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.