Jest.js 将Axios v0.27.2升级到v1.6.2时出现的问题

oxcyiej7  于 11个月前  发布在  Jest
关注(0)|答案(1)|浏览(224)

我正在使用适配器更改Axios的结果状态以更改结果状态。

import axios, { AxiosAdapter, AxiosError, AxiosResponse } from "axios";
import httpAdapter from "axios/lib/adapters/http";
import settle from "axios/lib/core/settle";

const customAdapter = (config) =>
  new Promise((resolve, reject) => {
    httpAdapter(config)
      .then(async response => {
        const jsonResponse = JSON.parse(response.data);
        if (jsonResponse.error) {
          if (
            jsonResponse.error.code === 12345 
          ) {
            response.status = 401;
          }  else {
            response.status = 503;
          }
        }

        settle(resolve, reject, response);
      })
      .catch(reject);
  });

const apiInstance = axios.create({
  baseURL:"/api"
});

apiInstance.defaults.adapter = customAdapter as AxiosAdapter;

export default apiInstance;

字符串
在新版本的Axios中,我们不支持httpAdapter,它存在于“axios/unsafe/adapters/http”中。它基本上不会从包中导出。(https://github.com/axios/axios/issues/5000#issuecomment-1521957205)
为此,您必须使用xhrAdapter。

import axios from "axios";
import xhrAdapter from "axios/unsafe/adapters/xhr";
import settle from "axios/unsafe/core/settle";

const apiInstance = axios.create({
  adapter: config =>
    new Promise((resolve, reject) => {
      xhrAdapter(config)
        .then(async response => {
          const jsonResponse = JSON.parse(response.data);
          if (jsonResponse.error) {
            if (
              jsonResponse.error.code === 12345 
            ) {
              response.status = 401;
            } else {
              response.status = 503;
            }
          }
          settle(resolve, reject, response);
        })
        .catch(reject);
    }),
  baseURL: "/api"
});


太棒了!!您现在已经解决了这个问题,如果您尝试运行此命令,您会注意到paramserializer也已更改,这意味着参数的API将类似于

http://localhost:3000/api/store?input[request][method]=GetStoreType&input[request][args][0]=m%40d


理想情况下,

http://localhost:3000/api/store?input=%7B%22request%22%3A%7B%22method%22%3A%22GetStoreType%22%2C%22args%22%3A%5B%22mr%40d


引用了这篇文章text并使用了以下代码:

axios.defaults.paramsSerializer = params =>
  Object.keys(params)
    .filter(key => params[key] !== undefined)
    .map(key => {
      if (Object.prototype.toString.call(params[key]) === "[object Object]") {
        params[key] = JSON.stringify(params[key]);
      }
      if (Array.isArray(params[key])) {
        return params[key].map((v: any) => `${key}[]=${encodeURIComponent(v)}`).join("&");
      }
      return `${key}=${encodeURIComponent(params[key])}`;
    })
    .join("&");


太棒了!!问题解决了。现在是测试用例。当你运行测试用例时,测试套件将失败,因为jest找不到模块'axios/unsafe/adapters/xhr'。
找到一篇关于jest在升级后无法工作的文章(https://github.com/axios/axios/issues/5101
在尝试修复(https://github.com/axios/axios/issues/5101)中提到的问题后,

1. "react-scripts test --transformIgnorePatterns \"node_modules/(?!axios)/\"",

Cannot find module 'axios/unsafe/adapters/xhr' 

2. "jest": {
    "moduleNameMapper": {
      "axios": "axios/dist/node/axios.cjs"
    }
  },

RangeError: Maximum call stack size exceeded
Exception in PromiseRejectCallback:
/home/project/node_modules/axios/dist/node/axios.cjs:3088
  return adapter(config).then(function onAdapterResolution(response) {
                         ^

RangeError: Maximum call stack size exceeded
Exception in PromiseRejectCallback:
node:internal/process/promises:107
function promiseRejectHandler(type, promise, reason) {
                             ^

s71maibg

s71maibg1#

您需要为未找到的模块提供模块Map器配置:

"jest": {
   "moduleNameMapper": {
     "axios/unsafe/adapters/xhr": "axios/lib/adapters/xhr.js",
     "axios/unsafe/core/settle": "axios/lib/core/settle.js"
   }
}

字符串

相关问题