You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jest测试中Axios拦截器代码未被覆盖,求100%覆盖率方案

解决Jest测试中Axios拦截器未计入覆盖率的问题

1. 确保测试中实际触发拦截器逻辑

拦截器代码只有在Axios发起请求/响应时才会执行,单纯Mock Axios实例不会触发拦截器。你需要在测试里显式调用请求方法(比如axios.get()),让拦截器代码完整执行一遍:

// 测试示例
import axios from './your-axios-instance-file';

test('请求拦截器正常执行', async () => {
  await axios.get('/test-url');
  // 断言拦截器的行为,比如检查headers是否被正确修改
  expect(axios.defaults.headers.common['Authorization']).toBeDefined();
});

2. 避免完全Mock Axios模块,保留自定义实例的拦截器

如果拦截器挂载在你自己创建的Axios实例上,不要直接jest.mock('axios')覆盖整个模块,而是导出你的自定义实例,只Mock实例的请求方法,保留拦截器的真实代码:

// 你的Axios配置文件(比如axiosConfig.js)
import axios from 'axios';
const instance = axios.create();
instance.interceptors.request.use(config => {
  config.headers.Authorization = 'Bearer token';
  return config;
});
export default instance;

// 测试文件
import axiosInstance from './axiosConfig';

// 只Mock请求方法,不影响拦截器
jest.spyOn(axiosInstance, 'get').mockResolvedValue({ data: {} });

test('请求拦截器逻辑被执行', async () => {
  await axiosInstance.get('/test');
  // 验证拦截器的fulfilled回调被调用
  expect(axiosInstance.interceptors.request.handlers[0].fulfilled).toHaveBeenCalled();
});

3. 检查Jest覆盖率配置是否排除了拦截器文件

打开jest.config.js,确认collectCoverageFrom包含了你的Axios配置文件,且没有被coveragePathIgnorePatterns排除:

// jest.config.js
module.exports = {
  collectCoverageFrom: [
    'src/**/*.js', // 确保包含拦截器所在的文件路径
  ],
  coveragePathIgnorePatterns: [
    // 不要把Axios配置文件加入忽略列表
  ]
};

4. 测试拦截器的错误分支

如果拦截器包含错误处理逻辑(比如interceptors.request.use(fulfilled, rejected)),要单独编写测试覆盖错误场景:

test('请求拦截器错误处理逻辑执行', async () => {
  const testError = new Error('请求异常');
  // 模拟拦截器成功回调抛出错误
  jest.spyOn(axiosInstance.interceptors.request.handlers[0], 'fulfilled').mockRejectedValue(testError);
  
  await expect(axiosInstance.get('/test')).rejects.toThrow(testError);
  // 验证错误拦截器被调用
  expect(axiosInstance.interceptors.request.handlers[0].rejected).toHaveBeenCalledWith(testError);
});

内容的提问来源于stack exchange,提问作者Prasad Parab

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 05:25:29