如何在使用@angular-builders/jest的Angular项目中用VSCode调试测试
解决Angular + @angular-builders/jest项目的VSCode测试调试问题
方案1:修正JestRunner扩展的配置
问题根源是JestRunner默认直接调用jest命令,但你的项目依赖Angular CLI builder做预处理,所以需要指定正确的jest命令和配置文件:
- 打开VSCode设置(快捷键
Ctrl+,),搜索jestrunner.jestCommand,设置为:npx jest --config ./jest.config.js - 同时设置
jestrunner.rootPath为你的项目根目录(比如${workspaceFolder}) - 如果项目没有单独的
jest.config.js,先参考方案3生成一个
方案2:使用VSCode原生调试配置(launch.json)
如果JestRunner还是有问题,直接用VSCode自带的调试功能更可靠:
- 在项目根目录创建
.vscode/launch.json,写入以下配置:
{ "version": "0.2.0", "configurations": [ { "name": "调试所有Jest测试", "type": "node", "request": "launch", "program": "${workspaceRoot}/node_modules/@angular-builders/jest/node_modules/jest/bin/jest.js", "args": [ "--runInBand", "--config", "${workspaceRoot}/jest.config.js" ], "cwd": "${workspaceRoot}", "console": "integratedTerminal", "internalConsoleOptions": "neverOpen" }, { "name": "调试当前测试文件", "type": "node", "request": "launch", "program": "${workspaceRoot}/node_modules/@angular-builders/jest/node_modules/jest/bin/jest.js", "args": [ "${relativeFile}", "--runInBand", "--config", "${workspaceRoot}/jest.config.js" ], "cwd": "${workspaceRoot}", "console": "integratedTerminal", "internalConsoleOptions": "neverOpen" } ] }
- 打开要调试的测试文件,在左侧调试面板选择
调试当前测试文件,点击启动按钮即可断点调试
- 注:
--runInBand参数强制Jest单进程运行,避免多进程调试时断点失效的问题
方案3:添加独立的Jest配置文件
部分@angular-builders/jest项目没有单独的jest.config.js,导致调试工具无法正确识别配置,需要手动添加:
在项目根目录创建jest.config.js,内容如下(根据你的项目调整):
module.exports = { preset: 'jest-preset-angular', setupFilesAfterEnv: ['<rootDir>/src/setup-jest.ts'], testPathIgnorePatterns: ['<rootDir>/node_modules/', '<rootDir>/dist/'], globals: { 'ts-jest': { tsconfig: '<rootDir>/tsconfig.spec.json', stringifyContentPathRegex: '\\.html$' } } };
同时检查tsconfig.spec.json,确保types数组包含jest:
{ "extends": "./tsconfig.json", "compilerOptions": { "outDir": "./out-tsc/spec", "types": ["jest"] }, "include": ["src/**/*.spec.ts", "src/**/*.d.ts"] }
额外排查点
- 暂时禁用VSCode中其他Jest相关插件(比如
Jest官方插件),避免冲突 - 执行
rm -rf node_modules dist && npm install,清理依赖后重新安装 - 检查项目中
jest、jest-preset-angular、@angular-builders/jest的版本是否兼容,尽量保持最新稳定版
内容的提问来源于stack exchange,提问作者Vincent Lagache
相关产品推荐
相关产品推荐

