如何使用 jest 测试 axios 拦截器?
Posted
技术标签:
【中文标题】如何使用 jest 测试 axios 拦截器?【英文标题】:How to test axios interceptors using jest? 【发布时间】:2019-04-28 08:52:14 【问题描述】:我正在尝试测试以下代码:
import axios from 'axios';
import history from './ReduxService';
axios.interceptors.response.use(response => response,
(error) =>
if ((error.response && error.response.status === 408) || error.code === 'ECONNABORTED')
history.push('/error');
return Promise.reject(error);
);
关于如何覆盖它的任何建议?
【问题讨论】:
【参考方案1】:首先,修改代码,让你可以在里面传递一个模拟版本的axios:
import axios, AxiosInstance from 'axios';
import history from './ReduxService';
export const addResponseInterceptor(client: AxiosInstance) =>
client.interceptors.response.use(response => response,
(error) =>
if ((error.response && error.response.status === 408) || error.code ===
'ECONNABORTED')
history.push('/error');
return Promise.reject(error);
);
;
然后像这样设置你的测试:
import addResponseInterceptor from './yourInterceptorFile'
import axios from 'axios';
jest.mock('axios', () =>
return
create: jest.fn(),
interceptors:
request:
use: jest.fn(),
eject: jest.fn(),
,
response:
use: jest.fn(),
eject: jest.fn(),
,
;
);
describe('addResponseInterceptor tests', () =>
beforeEach(() =>
(axios.create as jest.Mock).mockReset();
(axios.interceptors.request.use as jest.Mock).mockReset();
(axios.interceptors.request.eject as jest.Mock).mockReset();
(axios.interceptors.response.use as jest.Mock).mockReset();
(axios.interceptors.response.eject as jest.Mock).mockReset();
);
it('should add a response interceptor to the axios instance', () =>
addResponseInterceptor(axios);
expect(axios.interceptors.response.use).toHaveBeenCalled();
);
it('should push to history when an error occurs', async() =>
const historySpy = jest.spyOn(history, 'push');
const axiosClient = axios;
addResponseInterceptor(axios);
const interceptorErrorHandler = (axiosClient.interceptors.response.use as jest.Mock).mock.calls[0][1];
try
await interceptorErrorHandler(
response:
status: 408
);
//this should not be called--the promise should be rejected
expect(true).toBe(false);
catch
expect(historySpy).toHaveBeenCalledWith('/error');
);
. . .
);
【讨论】:
以上是关于如何使用 jest 测试 axios 拦截器?的主要内容,如果未能解决你的问题,请参考以下文章
如何在 React 应用程序中使用 JEST 测试向 api 发出 axios 请求的异步函数