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

Jest mock axios时TypeScript报错:不存在'mockResolvedValue'属性

问题原因

TypeScript 无法自动感知你已经将 axios.get 转换为 Jest 模拟函数,它仍然将 axios.get 识别为 axios 原生的请求方法,原生方法本身不存在 mockResolvedValue 这类 Jest 模拟函数专属的属性,因此抛出类型错误。

解决方案

你可以从以下几种方案中选择符合你项目习惯的实现:

方案1:使用内置的 jest.mocked 做类型转换(推荐)

Jest 26+ 内置了类型辅助工具 jest.mocked,可以在不丢失原有类型定义的前提下,标记目标函数为 Jest 模拟类型,是类型最安全的方案:

import axios from 'axios';
// 注意要先对整个 axios 模块做模拟
jest.mock('axios');

test('should fetch users', () => {
  const users = [{name: 'Bob'}];
  const resp = {data: users};
  // 用 jest.mocked 包装 axios.get
  jest.mocked(axios.get).mockResolvedValue(resp);

  return Users.all().then(data => expect(data).toEqual(users));
});

方案2:单次类型断言

如果只是临时用一次,可以直接对 axios.get 做类型断言,标记为 jest.Mock 类型:

(axios.get as jest.Mock).mockResolvedValue(resp);

方案3:全局标记整个 axios 为模拟类型

如果你的测试文件中需要频繁调用 axios 的多个模拟方法,可以提前将整个 axios 实例标记为 Jest 模拟类型,后续调用所有方法都不需要再单独处理类型:

import axios from 'axios';
jest.mock('axios');
// 全局标记 axios 为模拟类型
const mockAxios = axios as jest.Mocked<typeof axios>;

test('should fetch users', () => {
  const users = [{name: 'Bob'}];
  const resp = {data: users};
  mockAxios.get.mockResolvedValue(resp);

  return Users.all().then(data => expect(data).toEqual(users));
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 05:39:00