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

Angular 8 迁移Jest后npm run test命令执行失败求助

解决Angular 8迁移Jest时找不到tsconfig.spec.json的问题

嘿,我之前帮不少人处理过Angular迁移Jest的问题,你遇到的这个找不到tsconfig.spec.json的错误其实很常见,咱们一步步来解决它。

问题回顾

你在Angular 8项目中从Karma/Jasmine迁移到Jest框架,执行npm run test时碰到了这个错误:

File not found: /src/tsconfig.spec.json (resolved as: D:\app-jest\src\tsconfig.spec.json) at ConfigSet.resolvePath (node_modules/ts-jest/dist/config/config-set.js:712:19)

你的相关配置文件如下:

package.json

{ 
  "scripts": { 
    "ng": "ng", 
    "start": "ng serve", 
    "test": "jest" 
  } 
}

jest.config.js

module.exports = { 
  preset: 'jest-preset-angular', 
  roots: ['src'], 
  setupFilesAfterEnv: ["./src/setup-jest.ts"] 
};

问题根源

这个错误本质是Jest默认去src目录下找测试用的TypeScript配置文件,但Angular项目里默认的tsconfig.spec.json是放在项目根目录而非src目录下的,所以路径匹配不上。

解决方案

1. 检查/创建根目录的tsconfig.spec.json

首先确认你的项目根目录(和package.json同层级的文件夹)有没有tsconfig.spec.json。如果没有,直接创建一个,内容参考下面的模板(记得替换成Jest相关配置):

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/spec",
    "types": [
      "jest",
      "node"
    ],
    "esModuleInterop": true,
    "emitDecoratorMetadata": true
  },
  "files": [
    "src/test.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.spec.ts",
    "src/**/*.d.ts"
  ]
}

注意这里的types字段要改成jest和node,替换掉原来的Jasmine相关配置。

2. 修改jest.config.js指定正确的tsconfig路径

在你的Jest配置里新增tsConfig字段,明确指向根目录的tsconfig.spec.json,修改后的配置如下:

module.exports = { 
  preset: 'jest-preset-angular', 
  roots: ['src'], 
  setupFilesAfterEnv: ["./src/setup-jest.ts"],
  tsConfig: './tsconfig.spec.json' // 新增这一行,指定正确的配置文件路径
};

3. 确认setup-jest.ts文件存在且配置正确

检查src/setup-jest.ts是否存在,如果没有就创建它,里面只需要一行初始化代码:

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

这行代码用来加载Angular的Jest预设,确保测试环境能正常初始化。

4. 补全必要的Jest依赖

最后再确认你已经安装了所有必需的依赖,运行下面的命令安装:

npm install --save-dev jest jest-preset-angular @types/jest

如果项目里还残留着Karma/Jasmine的依赖,也可以顺手卸载掉(可选,但能避免潜在冲突):

npm uninstall karma karma-chrome-launcher karma-jasmine karma-jasmine-html-reporter jasmine-core @types/jasmine @types/jasminewd2

验证

完成以上步骤后,再运行npm run test,应该就能正常执行Jest测试了。

内容的提问来源于stack exchange,提问作者Lakshmikanth G.M

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:25:29