简体   繁体   English

(0, _axios.default) 不是 function 时 mocking axios 带拦截器

[英](0 , _axios.default) is not a function when mocking axios with interceptors

My app has a file which creates an instance of axios with interceptors and then the api's use this instance to make calls.我的应用程序有一个文件,它创建一个带有拦截器的 axios 实例,然后 api 使用这个实例进行调用。 The issue is when i try to write test for this api it fails with TypeError: (0, _axios.default) is not a function error.问题是当我尝试为此 api 编写测试时,它失败并出现TypeError: (0, _axios.default) is not a function错误。

below is the poc which creates the axios instance:下面是创建 axios 实例的 poc:

const axiosInstance = axios.create({
  timeout: 20000,
  paramsSerializer(params) {
    return qs.stringify(params, { indices: false });
  },
});

axiosInstance.interceptors.request.use((config) => {
  if (process.env.NODE_ENV === 'development') {
    logger.info(`Request sent to ${config.url}`, config.params);
  }

  return config;
}, (error) => Promise.reject(error));

axiosInstance.interceptors.response.use((response) => {
  if (process.env.NODE_ENV === 'development') {
    logger.info(`Response from ${response.config.url}`, response.data);
  }

  return parseBody(response);
}, (error) => parseError(error));

export default axiosInstance;

this is the api that uses the axios instance这是使用 axios 实例的 api

const triviaAPI = {
  getQuestions: async (amount) => axiosInstance({
    method: 'get',
    url: 'https://opentdb.com/api.php',
    params: {
      amount,
    },
  }).then((response) => response.results)
    .catch((error) => {
      throw error;
    }),
};

export default triviaAPI;

and this is the axios mock这是 axios 模拟

import mockAxios from 'jest-mock-axios';

export default {
  ...mockAxios,
  ...{
    create: jest.fn(() => ({
      ...mockAxios,
      defaults: {
        headers: {
          common: {},
        },
      },
      interceptors: {
        request: {
          use: jest.fn(),
        },
        response: {
          use: jest.fn(),
        },
      },
      get: jest.fn(() => Promise.resolve({ data: { total_payout: 100.21 } })),
    })),
  },
};

and finally this is the test case最后这是测试用例

describe('triviaAPI', () => {
  it('should return a successful response', async () => {
    const data = await triviaAPI.getQuestions(10);
    console.log(data);
    expect(Array.isArray(data)).toBe(true);
  });
});

when i run the test i get the below error当我运行测试时,出现以下错误在此处输入图像描述

I have searched around a lot but found no solution yet.我已经搜索了很多,但还没有找到解决方案。 Please help!!!请帮忙!!!

The reason it may not be working is because you are using export which isnt yet supported in nodejs by default you can however enable it using an experimental node.js feature as referenced here however thats not recommended therefore i would recommend using esm它可能无法正常工作的原因是因为您使用的是默认情况下在 nodejs 中尚不支持的export ,但是您可以使用此处引用的实验性 node.js 功能启用它但是不推荐,因此我建议使用esm

So for your use case:因此,对于您的用例:

package.json : package.json

{
  "name": "axios-test",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "test": "node -r esm ." //Important
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "axios": "^0.19.2",
    "esm": "^3.2.25" //Important
  }
}

axiosInstance.js : axiosInstance.js

import axios from "axios" //Important

const axiosInstance = axios.create({
    timeout: 20000,
    paramsSerializer(params) {
        return JSON.stringify(params, { indices: false });
    },
});

axiosInstance.interceptors.request.use((config) => {
    if (process.env.NODE_ENV === 'development') {
        logger.info(`Request sent to ${config.url}`, config.params);
    }

    return config;
}, (error) => Promise.reject(error));

axiosInstance.interceptors.response.use((response) => {
    if (process.env.NODE_ENV === 'development') {
        logger.info(`Response from ${response.config.url}`, response.data);
    }

    return response;
}, (error) => Promise.reject(error));

export default axiosInstance; //Important

main.js :主.js

import axiosInstance from "./axiosInstance.js" //Important

const triviaAPI = {
    getQuestions: async (amount) => axiosInstance({
        method: 'get',
        url: 'https://opentdb.com/api.php',
        params: {
            amount,
        },
    }).then((response) => response.results)
        .catch((error) => {
            throw error;
        }),
};

async function main() {
    const data = await triviaAPI.getQuestions(10);
    console.log(data);
}

main()

NOTICE : Some code was changed in my axiosInstance.mjs as the question didn't include what they were so I have marked all relevant changes with //Important注意:我的 axiosInstance.mjs 中的一些代码已更改,因为问题不包括它们是什么所以我用//Important标记了所有相关更改

Also : If you want to see an example using the experimental features please check the edit history of this answer.另外:如果您想查看使用实验功能的示例,请查看此答案的编辑历史记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM