如何用 jest 测试 axios 拦截器

2024-03-31

在我的项目中,我有一个命名空间,导出一些使用 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);
    }
);

我想测试这个拦截器是否按预期工作,我在这里搜索表单并用谷歌搜索了很多,但所有答案基本上都是在嘲笑拦截器而不是测试它。

我努力了:

  1. 模拟 axios post 请求的响应并检查返回的 AxiosPromise,但它只包含我模拟的结果。当我模拟使用时,它似乎忽略了拦截器mockResolvedValue.
  2. 我尝试向模拟的 axios 实例添加拦截器,但这也不起作用。

Thanks


将函数拉出来并在没有 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)

现在您可以测试 onFullfilled 和 onRejected 函数,并且对 axios 的依赖较少。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何用 jest 测试 axios 拦截器 的相关文章