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

运行Jest测试时报错:请勿在Jest测试环境外导入@jest/globals

解决Jest测试TypeScript时的@jest/globals导入错误

方案1:检查Jest配置文件

确保Jest能正确识别你的测试文件,在jest.config.js或jest.config.ts中确认规则匹配测试文件路径(比如你的文件在src/__tests__目录下),示例配置:

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  testMatch: ['**/__tests__/**/*.ts', '**/?(*.)+(spec|test).ts'],
  moduleFileExtensions: ['ts', 'js', 'json', 'node']
};

如果用TypeScript格式的配置文件,要确保已安装ts-node依赖。

方案2:替换@jest/globals导入为全局Jest对象

Jest默认会在测试环境中注入describe、test、expect等全局方法,你可以直接移除@jest/globals的导入语句:

import {NewMarketContractRequest, NewContractReponse, MarketSalesDataReply, MessageResonse} from '../models';
// 删掉这行:import {describe, expect, test} from '@jest/globals';

import {deployNewMarketContract} from '../market-contract-lib';

describe('deployNewMarketContract', () => {
    test('should deploy a new market contract', async () => {
        // 测试代码保持不变
    });
});

如果TypeScript报错找不到这些全局类型,在tsconfig.json中添加Jest类型引用:

{
  "compilerOptions": {
    "types": ["jest"]
  }
}

还没装类型包的话先安装:

npm install --save-dev @types/jest

方案3:修复ES模块与CommonJS的兼容性

如果项目package.json里设置了"type": "module",需要给Jest配置ES模块支持:

  1. 在jest.config.js中添加:
module.exports = {
  // 其他已有配置...
  transform: {
    '^.+\\.tsx?$': ['ts-jest', { useESM: true }]
  },
  extensionsToTreatAsEsm: ['.ts']
};
  1. 同步调整tsconfig.json的模块配置:
{
  "compilerOptions": {
    "module": "ESNext",
    "moduleResolution": "NodeNext"
  }
}

方案4:清理缓存并重装依赖

缓存或损坏的依赖也可能引发这类问题,执行以下命令重置:

# 清理Jest缓存
npx jest --clearCache

# 删除依赖目录和锁文件后重装
rm -rf node_modules package-lock.json
npm install

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 15:15:38