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

Jest从外部文件导入Mock类到jest.mock时抛出TypeError

Jest 拆分外部Mock实现不生效问题修复

根因

Jest 会自动将jest.mock()的工厂函数提升到测试文件的最顶层执行,执行优先级高于所有import导入语句。顶层导入的ClassMock在mock工厂运行时还未完成初始化,值为undefined,因此抛出TypeError: Cannot read property 'ClassMock' of undefined错误。

可行修复方案

方案1:在mock工厂内部通过require加载外部mock实现

删除测试文件顶层对ClassMock的import语句,直接在jest.mock的工厂函数内使用require同步加载外部mock文件,确保执行工厂逻辑时能正确拿到mock实现:

jest.mock('external-lib', () => {
  const originalModule = jest.requireActual('external-lib');
  // 工厂内部同步引入外部mock
  const { ClassMock } = require('./mocks');

  return {
    __esModule: true,
    ...originalModule,
    StrategyComputation: jest.fn(ClassMock),
  };
});

方案2:先初始化mock桩,导入完成后再绑定实现

先调用jest.mock初始化模块mock桩,等待所有import语句加载完成后,再通过mockImplementation绑定拆分到外部的构造函数逻辑:

import { ClassMock } from './mocks';
// 先初始化mock,保留原模块其他导出
jest.mock('external-lib', () => ({
  __esModule: true,
  ...jest.requireActual('external-lib'),
  StrategyComputation: jest.fn()
}));
import { StrategyComputation } from 'external-lib';

// 所有依赖加载完成后绑定mock实现
beforeAll(() => {
  (StrategyComputation as jest.Mock).mockImplementation(ClassMock);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 04:31:04