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

VSCode调试Jest:配置同时适配测试文件与被测试文件

解决VS Code Jest配置同时支持测试文件与被测试文件运行的问题

解决方案

修改launch.json中的args数组,添加--findRelatedTests参数,让Jest自动根据当前打开的文件查找关联测试用例执行。

修改后的完整配置:

{
  "type": "node",
  "request": "launch",
  "name": "Current Test File",
  "program": "${workspaceRoot}/node_modules/jest/bin/jest.js",
  "args": [
    "--verbose", 
    "-i", 
    "--no-cache",
    "--findRelatedTests",
    "${file}"
  ],
  "console": "integratedTerminal",
  "internalConsoleOptions": "neverOpen"
}

原理说明

  • 原配置直接将${file}作为Jest的目标文件,仅当文件是测试文件(如foo.spec.js)时才能被识别执行;
  • 添加--findRelatedTests参数后,Jest会自动适配两种场景:
    • 当前是测试文件时,直接执行该测试文件;
    • 当前是被测试文件(如foo.js)时,自动查找与之对应的测试文件(如foo.spec.js)并执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 04:12:04