[英]TypeError: (0 , _axios.default) is not a function when use jest.mock('axios') inside a *.test.js file
[英](0 , _axios.default) is not a function when mocking axios with interceptors
我的應用程序有一個文件,它創建一個帶有攔截器的 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);
});
});
我已經搜索了很多,但還沒有找到解決方案。 請幫忙!!!
它可能無法正常工作的原因是因為您使用的是默認情況下在 nodejs 中尚不支持的export
,但是您可以使用此處引用的實驗性 node.js 功能啟用它但是不推薦,因此我建議使用esm
因此,對於您的用例:
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 :
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
標記了所有相關更改
另外:如果您想查看使用實驗功能的示例,請查看此答案的編輯歷史記錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.