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

如何在VS Code中调试Angular基于Jest的TypeScript测试并解决断点偏移问题

断点偏移问题核心原因

TypeScript编译生成的SourceMap与运行时代码映射不匹配,且VS Code调试配置的编译产物路径映射错误。以下是完整调整方案:


1. 修改tsconfig.spec.json配置

新增SourceMap生成相关配置,确保编译后输出与源码对应的映射文件:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "outDir": "../out-tsc/spec",
    "module": "commonjs",
    "types": ["jest", "node"],
    // 新增以下2行
    "sourceMap": true,
    "inlineSources": true
  },
  "files": ["src/test.ts", "src/polyfills.ts"],
  "include": ["src/**/*.spec.ts", "src/**/*.d.ts"]
}

2. 修改package.json中的Jest配置

开启Jest侧SourceMap支持,避免编译后行号偏移:

"jest": {
  "preset": "jest-preset-angular",
  "setupFilesAfterEnv": [
    "<rootDir>/setupJest.ts"
  ],
  "moduleDirectories": [
    "node_modules",
    "./"
  ],
  "testResultsProcessor": "jest-teamcity-reporter",
  "testMatch": [
    "**/app/**/*.spec.ts"
  ],
  // 新增以下4行
  "sourceMaps": true,
  "retainLines": true,
  "transform": {
    "^.+\\.(ts|js|html)$": "jest-preset-angular"
  }
}

3. 修改.vscode/launch.json配置

修正编译产物路径匹配规则,优化调试逻辑:

{
  "name": "Tests",
  "type": "node",
  "request": "launch",
  "program": "${workspaceRoot}/node_modules/jest-cli/bin/jest.js",
  "stopOnEntry": false,
  // 新增--no-cache禁用Jest缓存,避免旧编译结果干扰
  "args": ["-i", "-o", "--no-cache"],
  "cwd": "${workspaceRoot}",
  "preLaunchTask": null,
  "runtimeExecutable": null,
  "env": {
    "NODE_ENV": "test"
  },
  "console": "integratedTerminal",
  // 修改outFiles路径,匹配tsconfig.spec中声明的编译输出目录
  "outFiles": ["${workspaceRoot}/out-tsc/spec/**/*.js"],
  "sourceMaps": true,
  // 新增以下2行优化调试体验,自动跳过无映射的第三方代码
  "smartStep": true,
  "skipFiles": ["<node_internals>/**", "${workspaceFolder}/node_modules/**/*"]
}

4. 配置生效操作

  • 执行npx jest --clearCache清理Jest本地缓存
  • 重启Visual Studio Code确保所有配置加载完成
  • 重新在TypeScript源码中设置断点启动调试即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 05:15:02