Isl*_*tom 16 javascript typescript jestjs axios
在我的项目中,我有一个命名空间,它导出一些使用 Axios 的函数,在同一个文件中,我向 axios 实例添加一个拦截器,如下所示:
axios.interceptors.response.use(
(res) => res,
(error) => {
if (
error.response &&
(error.response.status?.toString() === "400" ||
error.response.status?.toString() === "403" ||
error.response.status?.toString() === "404")
) {
return Promise.reject(
Error(JSON.stringify(error.response.data?.status?.errors[0]))
);
} else if (error.response) {
return Promise.reject(
Error(
`server responsed with the following code: ${error.response?.status} and the following message: ${error.response?.statusText}`
)
);
} else if (error.request) {
return Promise.reject(
Error(
"The request was made but no response was received, check your network connection"
)
);
} else Promise.reject(error);
}
);
Run Code Online (Sandbox Code Playgroud)
我想测试这个拦截器是否按预期工作,我在这里搜索表单并用谷歌搜索了很多,但所有答案基本上都是在嘲笑拦截器而不是测试它。
我努力了:
mockResolvedValue。谢谢
小智 4
将函数拉出来并在没有 axios 的情况下进行测试怎么样?
import axios, { AxiosError, AxiosResponse } from 'axios'
export const onFulfilled = (response: AxiosResponse) => {
// Your interceptor handling a successful response
}
export const onRejected = (error: AxiosError) => {
// Your interceptor handling a failed response
}
axios.interceptors.response.use(onFulfilled, onRejected)
Run Code Online (Sandbox Code Playgroud)
现在您可以测试 onFullfilled 和 onRejected 函数,并且对 axios 的依赖较少。
| 归档时间: |
|
| 查看次数: |
21277 次 |
| 最近记录: |