确保模拟拦截器,axios.create
如果使用:
// Replace any instances with the mocked instance (a new mock could be used here instead):
axios.create.mockImplementation((config) => axios);
// Mock out the interceptor (assuming there is only one):
let requestCallback = () => {
console.log("There were no interceptors");
};
axios.interceptors.request.use.mockImplementation((callback) => {
requestCallback = callback;
});
// Mock out the get request so that it returns the mocked data but also calls the
// interceptor code:
axios.get.mockImplementation(() => {
requestCallback();
return {
data: "this is some data"
};
});
请注意,如果这不起作用:
此示例假定创建和拦截器调用位于 Jest 可以模拟它们的位置。将axios.create
或axiosInstance.interceptors.request.use
行放在函数范围之外可能会导致上述模拟失败。这是一个示例文件,Jest 可以在其中模拟它们:
const axios = require('axios');
const DEBUG = true;
const customRequest = (url) => {
// Example of axios.create from https://www.npmjs.com/package/axios#axioscreateconfig
const axiosInstance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
// Example of interceptor taken from https://stackoverflow.com/a/52737325/7470360:
axiosInstance.interceptors.request.use((config) => {
if (DEBUG) { console.info("Request called", config); }
return config;
}, (error) => {
if (DEBUG) { console.error("Request error ", error); }
return Promise.reject(error);
});
return axiosInstance.get(url);
}
module.exports = customRequest;
该嘲讽代码将模拟出的axios.create
呼叫,axiosInstance
在通话customRequest
。将创建或拦截移动到函数之外将导致模拟失败。