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

Jest执行TypeScript命名空间测试遇语法错误,求解决方案

解决Jest执行TypeScript命名空间测试时的语法错误

你的问题核心是Jest没有使用ts-jest来转换TypeScript测试文件,导致默认的Babel解析器无法识别TypeScript特有的旧命名空间语法(module X.Y.Z),从而抛出语法错误。下面是具体的修复步骤:

1. 启用ts-jest的转换配置

你的Jest配置里注释掉了transform选项,这是问题的关键。Jest默认用Babel处理文件,但Babel不支持TypeScript的module命名空间语法。恢复transform配置,让.ts文件通过ts-jest编译:

修改后的jest.config.js:

module.exports = { 
  globals: { 
    'ts-jest': { "tsConfig": "<rootDir>/tsconfig.test.json" } 
  }, 
  transform: { 
    "\\.(ts|js)x?$": "ts-jest", 
  }, 
  coverageDirectory: "coverage", 
  testEnvironment: "jsdom", 
  testMatch: [ '<rootDir>/**/__tests__/**/*.ts' ] 
};

2. 优化tsconfig的文件覆盖范围

你的tsConfig.test.json已经配置了兼容旧命名空间的参数(target: es5、moduleResolution: classic),但可以补充添加测试文件的路径,确保ts-jest能正确识别并编译测试代码:

{ 
  "compileOnSave": false, 
  "compilerOptions": { 
    "allowJs": true, 
    "moduleResolution": "classic", 
    "inlineSources": true, 
    "declaration": true, 
    "emitDecoratorMetadata": true, 
    "experimentalDecorators": true, 
    "target": "es5", 
    "typeRoots": [ "node_modules/@types", "./node_modules/typescript/lib/lib.d.ts" ] 
  }, 
  "files": [ "./src/source.ts" ],
  "include": [ "./__tests__/**/*.ts" ]
}

3. 确保依赖完整性

如果还未安装必要的依赖包,执行以下命令补全:

npm install --save-dev ts-jest typescript @types/jest

验证修复

现在重新运行Jest命令:

npx jest

测试应该能正常执行——ts-jest会把TypeScript的命名空间语法编译成JavaScript可识别的代码,彻底避免Babel的解析错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:45:34