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

Angular从10.1升级到11/12后Karma/Jasmine测试运行报错

解决方案步骤

  • 第一步:修正test.ts导入顺序
    确保import 'zone.js/testing';是该文件的第一行导入语句,所有其他导入(包括Angular测试工具、环境变量、第三方依赖导入)都要放在这行之后,示例的正确结构如下:
// 首行必须是zone测试包导入
import 'zone.js/testing';
import { getTestBed } from '@angular/core/testing';
import {
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';

// 剩余其他导入放在此处
  • 第二步:清理并重新安装依赖
    删除项目根目录下的node_modules文件夹、package-lock.json文件,执行以下命令重新安装依赖,避免依赖缓存导致的路径识别异常:
npm cache clean --force
npm install
  • 第三步:添加路径别名兼容旧导入
    如果有第三方依赖还在使用旧的zone.js/dist/zone-testing导入路径,在tsconfig.json的compilerOptions中添加别名配置统一重定向:
{
  "compilerOptions": {
    // 其他原有配置保留
    "paths": {
      "zone.js/dist/zone-testing": ["node_modules/zone.js/testing"]
    }
  }
}
  • 第四步:执行官方迁移脚本修正遗漏配置
    运行Angular官方迁移工具自动适配版本配置,避免手动修改配置的遗漏项:
ng update @angular/cli @angular/core --migrate-only --from=10 --to=12

完成以上步骤后重新执行ng test即可正常运行测试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 05:15:08