我正在尝试使用 moxios 和 jest 测试对我的 axios 请求调用之一的拒绝。方法调用(调用 axios.get)会抛出错误,但不会调用 catch 块。
我的测试代码片段如下所示,
it('should call errorHandler method when request is rejected', done => {
const errorResp = {
status: 400,
response: {message: 'invalid data'}
};
let mockFunction = jest.fn();
Axios.getRaw('/test').then(mockFunction);
moxios.wait(async () => {
let req = moxios.requests.mostRecent();
try {
let rejection = await req.reject(errorResp);
console.log('rejection', rejection);// rejection is undefined
done();
} catch (e) {
console.log(e);
// test assertions
done(e);
}
})
});
getRaw 方法,
const API_WRAPPER = TryCatchHandler.genericTryCatch;
export default {
getRaw: path => API_WRAPPER(axios.get(`${SERVER_DOMAIN}${path}`)),
}
API_WRAPPER 方法,
export default {
genericTryCatch: async (executionMethod) => {
try {
const response = await executionMethod;
return response;
} catch (error) {
return ApiError.errorHandler(error);
}
}
}
errorHandler 方法,
export default {
errorHandler: error => {
const {status} = error;
switch (status) {
case 400:
case 401:
case 403:
case 404:
case 409:
case 417:
case 500:
case 502:
console.log("Error Handler says:", error);
return error.response.data;
default:
console.log("Error Handler says:", error);
let errorObj = {
errorMsg: error.message,
stack: error.stack
};
return errorObj;
}
}
}
由于未调用 catch 块,因此我无法断言我的测试用例。如何调用 catch?