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

TypeScript项目用Jest Mock node-fetch遇类型及运行时错误求助

解决jest-fetch-mock在TypeScript中的编译与运行错误

问题分析

你遇到的两个问题本质是依赖版本冲突和类型定义未正确加载:

  • TS2339: Property 'toHaveFetched' does not exist:jest-fetch-mock的自定义匹配器类型未被TypeScript识别
  • TypeError: require(...).sandbox is not a function:fetch-mock与jest-fetch-mock版本不兼容,后者已废弃sandbox方法,同时安装两个包引发冲突

解决方案步骤

1. 清理冲突依赖

jest-fetch-mock已内置fetch-mock的核心功能,无需单独安装fetch-mock及其类型包,先卸载冲突依赖:

npm uninstall -D fetch-mock @types/fetch-mock

重新安装正确的依赖组合:

npm install -D typescript node-fetch jest jest-fetch-mock @types/jest @types/node-fetch @types/jest-fetch-mock

2. 配置TypeScript识别jest-fetch-mock类型

修改tsconfig.json,在compilerOptions.types中添加jest-fetch-mock,让TypeScript加载其自定义匹配器的类型定义:

{
  "compilerOptions": {
    "target": "ESNext",
    "module": "CommonJS",
    "outDir": "./build",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "types": ["jest", "jest-fetch-mock"]
  },
  "include": ["src/**/*", "__tests__/**/*"]
}

3. 修正测试文件的Mock初始化方式

新版本jest-fetch-mock已移除sandbox方法,直接使用fetchMock的内置方法即可,示例测试代码如下:

import fetchMock from 'jest-fetch-mock';
import { yourFunctionToTest } from '../src/your-file';

// 测试前重置Mock状态
beforeEach(() => {
  fetchMock.resetMocks();
});

test('验证fetch调用逻辑', async () => {
  // Mock接口响应内容
  fetchMock.mockResponseOnce(JSON.stringify({ id: 1, name: 'test' }));

  // 执行待测试函数
  const result = await yourFunctionToTest();

  // 验证调用次数与参数
  expect(fetchMock).toHaveBeenCalledTimes(1);
  expect(fetchMock).toHaveBeenCalledWith('https://your-api-endpoint.com', {
    method: 'GET',
    headers: { 'Content-Type': 'application/json' }
  });

  // 使用toHaveFetched验证请求(类型生效后可正常使用)
  expect(fetchMock).toHaveFetched('https://your-api-endpoint.com', {
    method: 'GET'
  });

  // 验证函数返回结果
  expect(result).toEqual({ id: 1, name: 'test' });
});

验证结果

完成上述步骤后:

  • 编译时toHaveFetched的类型错误会消失
  • 运行时sandbox is not a function的错误也会被解决
  • 可正常使用jest-fetch-mock的所有匹配器验证Mock结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 21:06:26