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

升级Jest至29.5.0后模块Mock失效,求问题排查方案

Jest 29升级后模块Mock失效的解决方案

你的问题核心是Jest 29配合ts-jest 29.x时,ESM风格的模块Mock未被正确识别,导致导入的isTestPartnerId为undefined。以下是几个可行的排查和解决方向:

1. 调整Mock写法,使用jest.spyOn替代全模块Mock

直接mock整个ES模块在Jest 29+ts-jest的组合中容易出现导出结构不匹配的问题,换成jest.spyOn单独mock目标函数更可靠:

import * as utility from './utility';

describe('test mock', () => {
  it('should print true', async () => {
    jest.spyOn(utility, 'isTestPartnerId')
      .mockImplementation(async (base, context, id) => Promise.resolve(id === 'testPartnerId'));
    
    console.log(await utility.isTestPartnerId(null, null, 'testPartnerId'));
  });
});

2. 修复全模块Mock的导出结构

如果坚持使用全模块Mock,需要确保mock对象的导出结构与原模块完全一致,同时保留原模块的其他导出(如果有的话),避免TS/Jest解析时丢失导出项:

import { isTestPartnerId } from './utility';

jest.mock('./utility', () => ({
  __esModule: true,
  // 先导入原模块的所有导出,再覆盖目标函数
  ...jest.requireActual('./utility'),
  isTestPartnerId: jest.fn(async (base, context, id) => Promise.resolve(id === 'testPartnerId'))
}));

describe('test mock', () => {
  it('should print true', async () => {
    console.log(await isTestPartnerId(null, null, 'testPartnerId'));
  });
});

3. 检查Jest与ts-jest的配置一致性

确保你的jest.config.js和tsconfig.json配置适配Jest 29的要求:

  • jest.config.js中正确设置preset和transform:
module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  transform: {
    '^.+\\.tsx?$': 'ts-jest',
  },
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
};
  • tsconfig.json中开启esModuleInterop和allowSyntheticDefaultImports:
{
  "compilerOptions": {
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    // 其他配置...
  }
}

4. 清理Jest缓存

Jest 29的缓存机制可能残留旧的mock数据,执行以下命令清除缓存后重新测试:

jest --clearCache

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 22:02:25