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

VS Code调试Jest测试报错:无法找到jest-environment-node模块

解决Jest Runner调试并发测试时的环境路径错误问题

问题重现

环境结构:

root-dir
  test
    sample.spec.ts
  jest.config.js
  package.json
  tsconfig.json

测试代码(sample.spec.ts):

describe('Sample', () => {
  it.concurrent('App', async () => {
    expect(true).toEqual(true); // 此处设置了断点
  });
});

使用VS Code的Jest Runner扩展点击「Debug」按钮调试时,抛出异常:

Exception has occurred: Error: Cannot find module 'jest-environment-\node_modules\jest-environment-node\build\index.js/package.json' from ''

解决方案

1. 升级Jest Runner扩展到最新版本

这个路径拼接错误是Jest Runner扩展的已知bug,部分旧版本在处理it.concurrent时会错误拼接环境模块路径。打开VS Code扩展面板,找到Jest Runner,点击「更新」按钮升级到最新版后重试。

2. 在jest.config.js中显式指定测试环境

手动指定testEnvironment,避免扩展自动推导路径时出错:

// jest.config.js
module.exports = {
  // 其他配置...
  testEnvironment: 'node',
};

3. 手动配置VS Code调试launch.json

如果升级扩展后问题仍存在,直接绕过Jest Runner的自动调试配置,手动创建.vscode/launch.json:

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Jest Current File",
      "program": "${workspaceFolder}/node_modules/jest/bin/jest.js",
      "args": [
        "${relativeFile}",
        "--runInBand",
        "--watchAll=false"
      ],
      "console": "integratedTerminal",
      "internalConsoleOptions": "neverOpen",
      "disableOptimisticBPs": true,
      "env": {
        "NODE_ENV": "test"
      }
    }
  ]
}

配置完成后,打开测试文件,在VS Code调试面板选择「Jest Current File」启动调试。

4. 清除Jest缓存

执行以下命令清除Jest的缓存文件,避免缓存的错误路径残留:

npx jest --clearCache

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 17:45:46