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

Angular 13升级后Jest单元测试失败问题求助

Angular 13升级后Jest测试报错"Cannot find module '@angular/core/testing'"的解决方案

问题原因

当前使用的jest-preset-angular@8.1.0仅适配Angular 12及以下版本,与Angular 13的测试模块结构不兼容,导致无法解析@angular/core/testing。

解决步骤

1. 升级Jest相关依赖到适配Angular 13的版本

执行以下命令卸载旧依赖并安装兼容版本:

npm uninstall jest jest-preset-angular ts-jest @types/jest jest-environment-jsdom-fourteen
npm install --save-dev jest@27 jest-preset-angular@11 ts-jest@27 @types/jest@27

版本对应关系:Angular 13 → jest-preset-angular 11.x、jest 27.x、ts-jest 27.x

2. 更新Jest配置

修改package.json中的jest配置块:

  • 添加testEnvironment字段,替换原有的jest-environment-jsdom-fourteen依赖
  • 简化globals中的ts-jest配置,移除过时的astTransformers设置

更新后的jest配置示例:

"jest": {
  "preset": "jest-preset-angular",
  "roots": [
    "src"
  ],
  "transform": {
    "^.+\\.(ts|js|html)$": "ts-jest"
  },
  "transformIgnorePatterns": [
    "node_modules/(?!@ngrx)"
  ],
  "setupFiles": [
    "jest-canvas-mock"
  ],
  "setupFilesAfterEnv": [
    "<rootDir>/src/setupJest.ts"
  ],
  "moduleNameMapper": {
    "@app/(.*)": "<rootDir>/src/app/$1",
    "@assets/(.*)": "<rootDir>/src/assets/$1",
    "@authentication/(.*)": "<rootDir>/src/app/core/authentication/$1",
    "@core/(.*)": "<rootDir>/src/app/core/$1",
    "@environments/(.*)": "<rootDir>/src/environments/$1",
    "@home/(.*)": "<rootDir>/src/app/areas/home/$1",
    "@layout/(.*)": "<rootDir>/src/app/layout/$1",
    "@node_modules/(.*)": "<rootDir>/node_modules/$1",
    "@root-store/(.*)": "<rootDir>/src/app/root-store/$1",
    "@shared/(.*)": "<rootDir>/src/app/shared/$1",
    "@src/(.*)": "<rootDir>/src/$1",
    "@vendor/(.*)": "<rootDir>/src/vendor/$1"
  },
  "reporters": [
    "default",
    "jest-junit"
  ],
  "coverageReporters": [
    "cobertura",
    "text",
    "html"
  ],
  "testEnvironment": "jsdom",
  "globals": {
    "ts-jest": {
      "tsConfig": "<rootDir>/src/tsconfig.spec.json",
      "stringifyContentPathRegex": "\\.html$"
    }
  }
}

3. 检查并修复setupJest.ts

确保src/setupJest.ts中的导入语句正确:

import 'jest-preset-angular/setup-jest';

4. 清理缓存并重新安装依赖

rm -rf node_modules package-lock.json
npm install
npx jest --clearCache

验证

执行测试命令验证修复效果:

npm run test

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 22:20:28