javascript - (0 , _axios.default) 在使用拦截器模拟 axios 时不是函数
问题描述
我的应用程序有一个文件,它创建一个带有拦截器的 axios 实例,然后 api 使用这个实例进行调用。问题是当我尝试为此 api 编写测试时,它失败并TypeError: (0 , _axios.default) is not a function
出现错误。
下面是创建 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;
这是使用 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;
这是 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 } })),
})),
},
};
最后这是测试用例
describe('triviaAPI', () => {
it('should return a successful response', async () => {
const data = await triviaAPI.getQuestions(10);
console.log(data);
expect(Array.isArray(data)).toBe(true);
});
});
我已经搜索了很多,但还没有找到解决方案。请帮忙!!!
解决方案
它可能无法正常工作的原因是因为您使用export
的是默认情况下在 nodejs 中尚不支持的,但是您可以使用此处引用的实验性 node.js 功能启用它但是不建议这样做,因此我建议使用esm
因此,对于您的用例:
包.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:
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
主.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()
注意:我的 axiosInstance.mjs 中的一些代码已更改,因为问题不包括它们是什么,因此我已将所有相关更改标记为//Important
另外:如果您想查看使用实验功能的示例,请查看此答案的编辑历史记录。
推荐阅读
- sql - 在同一查询中使用查询结果字段作为数据库名称
- tensorflow - Tensorflow dense_image_warp 无法转换类型的对象
张量 - django - 将数据添加到数据库后更新 Django 表单
- auth0 - Auth0 PasswordLess - 在锁定 11 中为用户提供电子邮件和短信验证选项
- .htaccess - Redirect all pages ( from a server to another's homepage) except one
- active-directory - Active Directory 中“人员”和“用户”OU 之间的区别
- node.js - How to use Ziggy package in Typescript
- django - Python django 添加多个数据库
- c# - Unity 新手,Debug.Log 未显示在控制台上
- c++ - for循环在c ++中更改数组的值