如何使用 jest.mock('axios') 模拟拦截器?
2020-02-26
40446
使用 jest 运行测试时,我有基本的测试套件语法:
jest.mock('axios');
describe('app', () => {
let render
beforeEach(() => {
axiosMock.get.mockResolvedValueOnce({
data: {greeting: 'hello there'},
}),
render= renderApp()
});
test('should render something', () => {
expect(something).toBeInTheDocument();
});
});
问题是我的代码中有拦截器,使用 jest 命令运行测试时输出:
TypeError: Cannot read property 'interceptors' of undefined
并指向拦截器对象
axiosInstance.interceptors.request.use(...
axiosInstance
是存储
axios.create
返回值的变量
export const axiosInstance = axios.create({...
参考了 SO 上的这个 axios 线程 如何在 jest 中测试 axios 但它不涉及任何拦截器所以并没有什么帮助。
3个回答
最后这就足够了,简单明了
jest.fn()
jest.mock('axios', () => {
return {
interceptors: {
request: { use: jest.fn(), eject: jest.fn() },
response: { use: jest.fn(), eject: jest.fn() },
},
};
});
EugenSunic
2020-02-27
下面是我模拟
axios.create
及其
interceptors
的方式:
jest.mock('axios', () => {
return {
create: () => {
return {
interceptors: {
request: {eject: jest.fn(), use: jest.fn()},
response: {eject: jest.fn(), use: jest.fn()},
},
};
},
};
});
之后,我能够在测试代码中调用以下内容:
const client = axios.create({
baseURL: 'http://some-url.com',
});
client.interceptors.request.use(config => {
// some other test code
return config;
});
Benny Code
2021-05-11
如果使用拦截器和
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
中的调用。将创建或拦截移到函数之外将导致模拟失败。
A Jar of Clay
2020-02-26