【问题标题】:How to reverse backslashes in ${relativeFile} in Visual Studio Code in launch.json?如何在launch.json的Visual Studio Code中反转$ {relativeFile}中的反斜杠?
【发布时间】:2019-08-06 23:26:34
【问题描述】:

我正在尝试配置 (Windows) Visual Studio Code launch.json 以启动 jest 对当前文件的测试。为了获得路径,我使用了${relativeFile} 变量,它给出了一个带有类似"src\services\some-service.spec.ts" 的反斜杠的字符串,尽管在documentation 中,斜杠看起来很正常。

似乎jest 不接受这种路径,因为反斜杠。当我用普通斜杠手动传递相同的路径时,它工作得很好。

问题是有没有办法在 VSCode 路径预定义变量(如 ${relativeFile})中反转反斜杠,或者可能有一些解决方法?

【问题讨论】:

  • 我找到了on github。抱歉,我没看到,还没有解决。
  • 我看到了那个帖子,但我不知道他在哪里找到了那个例子,可能这只是一个想法。

标签: node.js configuration visual-studio-code jestjs


【解决方案1】:

[更新]2020-05-01

现在 jest cli 支持选项--runTestsByPath,因此您可以显式指定文件路径而不是模式,这允许您在 Windows 上使用\

所以下面的launch.json 应该可以工作:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Jest Current File",
      "type": "node",
      "request": "launch",
      "args": [
        "node_modules/jest/bin/jest.js",
        "--runInBand",
        "--runTestsByPath",
        "${relativeFile}"
      ],
      "console": "integratedTerminal",
      "internalConsoleOptions": "neverOpen",
      "cwd": "${workspaceFolder}"
    }
  ]
}

以下是原答案:


看来 jest 不打算与 \ 一起工作,vscode 也不打算提供替换预定义变量中的字符的功能。

但是有一些解决方法:

  1. 使用${fileBasename} 而不是${relativeFile}

  2. 或者使用input variables,让vscode在调试时提示你输入自定义测试名称。

这是上述两种解决方法的示例launch.json

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Jest Current FileBaseName",
      "type": "node",
      "request": "launch",
      "args": [
        "node_modules/jest/bin/jest.js",
        "--runInBand",
        "${fileBasename}"
      ],
      "console": "integratedTerminal",
      "internalConsoleOptions": "neverOpen",
      "cwd": "${workspaceRoot}"
    },
    {
      "name": "Jest Custom",
      "type": "node",
      "request": "launch",
      "args": [
        "node_modules/jest/bin/jest.js",
        "--runInBand",
        "${input:testName}"
      ],
      "console": "integratedTerminal",
      "internalConsoleOptions": "neverOpen",
      "cwd": "${workspaceRoot}"
    }
  ],
  "inputs": [
    {
      "type": "promptString",
      "id": "testName",
      "description": "The file or name you want to test",
      "default": "${fileBaseName}"
    }
  ]
}

【讨论】:

    【解决方案2】:

    这个问题与我给出的answer to elsewhere 非常相似。总结那里的解释:

    1. 不要直接运行node ...,而是运行bash -c node ...,这样您就可以在命令行中使用shell 命令替换。
    2. 通过cygpath -m 程序传递路径以获得正斜杠,例如$(cygpath -m ${relativeFile})

    有关更多详细信息和示例,请参阅链接的答案。

    【讨论】:

    • 这个答案拯救了我的一天。我正在使用 fileBasenameNoExtension 方法。然后我创建了一个通用命名的monorepo,这破坏了我从任何地方调试一个文件的能力。谢谢!
    【解决方案3】:

    使用扩展名command-variable 中的变量extension.commandvariable.file.relativeFilePosix,在需要${relativeFile} 的地方使用正斜杠。此扩展中还有其他有用的替换。

    【讨论】:

    • 使用 VS Code 通过调试器运行 jest 测试需要正斜杠,这是唯一有效的修复。非常感谢!
    猜你喜欢
    • 2016-04-16
    • 2017-02-25
    • 2013-11-10
    • 2012-10-03
    • 2015-03-29
    • 1970-01-01
    • 1970-01-01
    • 2018-05-19
    相关资源
    最近更新 更多