node.js 使用 Visual Studio Code 的摩卡断点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30023736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:43:17  来源:igfitidea点击:

Mocha breakpoints using Visual Studio Code

node.jsvisual-studio-codemochatdd

提问by André Vermeulen

Is it possible to add breakpoints to ones Mocha tests using Visual Studio Code?

是否可以使用 Visual Studio Code 向 Mocha 测试添加断点?

Normally when debugging code one need to configure the launch.json, setting the program attribute to the javascript file to execute. I am not sure how to do this for Mocha though.

通常在调试代码的时候需要配置launch.json,将program属性设置为javascript文件来执行。不过,我不确定如何为 Mocha 做到这一点。

采纳答案by Frank Nocke

Did you know, that you just go into your launch config, put your cursor after or between your other configs and press ctrl-spaceto get a current, valid mocha config auto-generated?

您知道吗,您只需进入启动配置,将光标放在其他配置之后或之间,然后按ctrl-space即可自动生成当前有效的 mocha 配置?

Which works perfectly fine for me. Including stopping at breakpoints. ( I also had a prior, now outdated one, that did no longer for various setting-related reasons. )

这对我来说非常好。包括在断点处停止。(我也有一个以前的,现在已经过时的,由于各种与设置相关的原因而不再使用。)

enter image description here

在此处输入图片说明

As of VSCode 1.21.1 (March 2018) this yields:

从 VSCode 1.21.1(2018 年 3 月)开始,结果如下:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Mocha (Test single file)",
      "type": "node",
      "request": "launch",
      "runtimeArgs": [
        "${workspaceRoot}/node_modules/.bin/mocha",
        "--inspect-brk",
        "${relativeFile}",
      ],
      "console": "integratedTerminal",
      "internalConsoleOptions": "neverOpen",
      "port": 9229
    }
}

On a side-note: debug-brkis deprectated(for anyone with Node >= Version 8 at least).

附带说明:debug-brk已弃用(至少对于 Node >= 版本 8 的任何人)。

回答by felixfbecker

If you don't want to use --debug-brk+Attach or state an absolute path to your global mocha installation (which will brake if you keep your launch.json under version control and have multiple developers on different machines), install mocha as a dev dependency and add this to your launch.json:

如果您不想使用--debug-brk+Attach 或声明全局 mocha 安装的绝对路径(如果您将 launch.json 置于版本控制之下并且在不同的机器上有多个开发人员,这将停止),请将 mocha 作为开发依赖项安装,并将此添加到您的launch.json:

{
  "name": "mocha",
  "type": "node",
  "request": "launch",
  "program": "${workspaceRoot}/node_modules/mocha/bin/_mocha",
  "stopOnEntry": false,
  "args": ["--no-timeouts", "--colors"], //you can specify paths to specific tests here
  "cwd": "${workspaceRoot}",
  "runtimeExecutable": null,
  "env": {
    "NODE_ENV": "testing"
  }
}

Full debugging support in your tests by just pressing F5.

只需按 F5,即可在测试中提供完整的调试支持。

--no-timeoutsmakes sure your tests don't time out because you stopped at a breakpoint, and --colorsmakes sure Mocha outputs colors even though it doesn't detect that VS Code supports colors.

--no-timeouts确保您的测试不会因为您在断点处停止而超时,并--colors确保 Mocha 输出颜色,即使它没有检测到 VS Code 支持颜色。

回答by Wolfgang Kluge

Another way is to use the --debug-brkcommand line option of mocha and the default Attachlaunch setting of the Visual Studio Code debugger.

另一种方法是使用--debug-brkmocha的命令行选项和AttachVisual Studio Code 调试器的默认启动设置。



Suggested deeper explanation (from André)

建议更深入的解释(来自安德烈)

To do this:

去做这个:

Run mocha from the command line using this command:

使用以下命令从命令行运行 mocha:

mocha --debug-brk

Now in VS Code click on the Debug icon, then select Attachfrom the option next to the start button. Add breakpoints in VS Code and then click start.

现在在 VS Code 中单击调试图标,然后Attach从开始按钮旁边的选项中进行选择。在 VS Code 中添加断点,然后单击开始。

回答by GPX

I've made this work on VSCode on OS X 10.10. Just replace your ./settings/launch.jsonfile with this.

我已经在 OS X 10.10 上的 VSCode 上完成了这项工作。只需./settings/launch.json用这个替换你的文件。

{
    "version": "0.1.0",
    "configurations": [
        {
            "name": "Run app.js",
            "type": "node",
            "program": "app.js", // Assuming this is your main app file.
            "stopOnEntry": false,
            "args": [],
            "cwd": ".",
            "runtimeExecutable": null,
            "env": { "NODE_ENV": "production"}
        },
        {
            "name": "Run mocha",
            "type": "node",
            "program": "/Users/myname/myfolder/node_modules/mocha/bin/_mocha",
            "stopOnEntry": false,
            "args": ["test/unit.js"],
            "cwd": ".",
            "runtimeExecutable": null,
            "env": { "NODE_ENV": "production"}
        }
    ]
}

It is also available as a gist here.

它也可在此处作为要点使用。

The key values you need to change are program, which should be set to the _mochaexecutable, and args, which should be an array of your test files.

您需要更改的键值是program,它应该设置为_mocha可执行文件,而args,它应该是测试文件的数组。

回答by mikebz

The way I got it to work on VS Code (1.8.2) on Mac OS X is:

我让它在 Mac OS X 上运行 VS Code (1.8.2) 的方式是:

{
    "name": "Mocha",
    "type": "node",
    "request": "launch",
    "program": "${workspaceRoot}/node_modules/mocha/bin/_mocha",
    "stopOnEntry": false,
    "args": ["--recursive"], //you can specify paths to specific tests here
    "cwd": "${workspaceRoot}",
    "runtimeExecutable": null,
    "env": {
        "NODE_ENV": "testing"
    }
}

Mocha needs to be installed in the npm modules directory.

Mocha 需要安装在 npm modules 目录下。

回答by Yas

  1. Go to Debug > Add Configuration...menu
  2. Select Node.jsenvironment
  3. Select Mocha Testsoption from the appeared drop-down list
  4. Type the path of your test file as the last item of the argsproperty
  5. Add a breakpoint
  6. Click on Debugicon
  7. Select Mocha Testsas a configuration
  8. Press Start debuggingbutton
  9. :-)
  1. 进入Debug > Add Configuration...菜单
  2. 选择Node.js环境
  3. Mocha Tests从出现的下拉列表中选择选项
  4. 键入测试文件的路径作为args属性的最后一项
  5. 添加一个 breakpoint
  6. 点击Debug图标
  7. 选择Mocha Tests作为配置
  8. 按下Start debugging按钮
  9. :-)

回答by Dário

I've figured out a way to do this which I classify as a workaround. I expect the Visual Studio Code team to provide a more definitive solution for this but meanwhile this what I've done:

我想出了一种方法来做到这一点,我将其归类为一种解决方法。我希望 Visual Studio Code 团队为此提供更明确的解决方案,但与此同时,我所做的是:

  1. I've created a ./settings/mocha.jsfile which runs mocha programatically passing arguments as a list of files to be run. You can see the full file here;
  2. I've created a launch config which will run the ./settings/mocha.jsas the programand passes the files/file patterns we need to test as arguments:

    {
        "name": "Unit tests",
        "type": "node",
        "program": ".settings/mocha.js",
        "stopOnEntry": true,
        "args": ["test/unit/*.js", "test/unit/**/*.js"],
        "cwd": ".",
        "runtimeExecutable": null,
        "env": { }
    }
    

    Full launch.json example

  1. 我创建了一个./settings/mocha.js文件,它以编程方式运行 mocha,将参数作为要运行的文件列表传递。你可以在这里看到完整的文件;
  2. 我创建了一个启动配置,这将运行./settings/mocha.jsprogram,并传递我们需要测试作为参数的文件/文件模式:

    {
        "name": "Unit tests",
        "type": "node",
        "program": ".settings/mocha.js",
        "stopOnEntry": true,
        "args": ["test/unit/*.js", "test/unit/**/*.js"],
        "cwd": ".",
        "runtimeExecutable": null,
        "env": { }
    }
    

    完整的 launch.json 示例

So this is the equivalent of doing mocha test/unit/*.js test/unit/**/*.jsand now we can use breakpoints in our mocha tests.

所以这相当于mocha test/unit/*.js test/unit/**/*.js现在我们可以在我们的 mocha 测试中使用断点。

回答by Eugene Kulabuhov

If you add ${file} variable at the end of the args list you can start debugging directly from the file you have open:

如果在 args 列表末尾添加 ${file} 变量,则可以直接从打开的文件开始调试:

        {
            "type": "node",
            "request": "launch",
            "name": "Mocha Tests",
            "program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
            "args": [
                "-u",
                "tdd",
                "--timeout",
                "999999",
                "--colors",
                "${file}"
            ],
            "internalConsoleOptions": "openOnSessionStart"
        }

回答by Alongkorn Chetasumon

in the launch.json, add 1 more configuration below

在 launch.json 中,在下面再添加 1 个配置

{
      "type": "node",
      "request": "launch",
      "name": "Mocha Tests",
      "program": "${workspaceRoot}/node_modules/mocha/bin/_mocha",
      "args": [
        "--timeout",
        "10000",
        "${workspaceRoot}/services/*.spec.js",
        "${workspaceRoot}/*.spec.js"
      ],
      "internalConsoleOptions": "openOnSessionStart"
    },

if you need to configure node version, simply add runtimeExecutablefield like this

如果您需要配置节点版本,只需添加这样的runtimeExecutable字段

{
      "type": "node",
      "request": "launch",
      "name": "Mocha Tests",
      "program": "${workspaceRoot}/node_modules/mocha/bin/_mocha",
      "args": [
        "--timeout",
        "10000",
        "${workspaceRoot}/services/*.spec.js",
        "${workspaceRoot}/*.spec.js"
      ],
      "internalConsoleOptions": "openOnSessionStart",
      "runtimeExecutable": "${env:HOME}/.nvm/versions/node/v8.2.1/bin/node"
    },

回答by Jon Adams

Sorry for adding yet another answer, but none of the previous ones quite worked for me as of VS Code 1.8.1 and the standard Node debugger included in it. Here is the way I solved it (with guidance from the previous answers here and from the official VS Code Node.js Debuggingdocs) so there is one click/keypress debugging:

很抱歉添加了另一个答案,但从 VS Code 1.8.1 和其中包含的标准 Node 调试器开始,之前的所有答案都不对我有用。这是我解决它的方法(根据这里之前的答案和官方VS Code Node.js 调试文档的指导),因此只需单击/按键调试:

  • Ensure mocha is installed as a devDependencyin packages.json: "devDependencies": { "mocha": "^3.2", ... }
  • Run npm installin the directory of your package.jsonto make sure mocha is now installed in node_modules/
  • Open .vscode/launch.json(or in VS Code, press F1, start typing "launch", and select "Debug: Open launch.json")
  • Click the blue "Add Configuration" button in the bottom right (or just copy and paste one of your others); this step is optional... I mean, you can re-use an existing config. But I suggest adding one to keep it less confusing.
  • Change the following in your launch.json, then pick the new config name in the debug window in VS Code and click the green arrow to start debugging your node + mocha tests!
  • 确保 mocha 安装为devDependencyin packages.json"devDependencies": { "mocha": "^3.2", ... }
  • npm install在您的目录中运行package.json以确保 mocha 现在安装在node_modules/
  • 打开.vscode/launch.json(或在 VS Code 中,按 F1,开始输入“launch”,然后选择“Debug: Open launch.json”)
  • 单击右下角的蓝色“添加配置”按钮(或只需复制并粘贴您的其他配置之一);这一步是可选的......我的意思是,你可以重新使用现有的配置。但我建议添加一个以减少混乱。
  • 在您的 中更改以下内容launch.json,然后在 VS Code 的调试窗口中选择新的配置名称,然后单击绿色箭头开始调试您的节点 + mocha 测试!

In the new config in launch.json:

在新配置中 launch.json:

"configurations": [{
    "name": "whatever name you want to show in the VS Code debug list",
    "type": "node",
    "cwd": "${workspaceRoot}",
    "program": "${workspaceRoot}/node_modules/mocha/bin/mocha",
    "args": ["--debug-brk=5858", "--no-timeouts", "--colors", "test/**/*.js"],
    "address": "localhost",
    "port": 5858,
    // the other default properties that are created for you are fine as-is
}, ...]

This assumes the pattern test/**/*.jswill work for where you put your tests. Change as appropriate.

这假设该模式test/**/*.js适用于您放置测试的位置。酌情更改。

Feel free to change the port as long as you change it in both of the argsand portproperties to match.

只要您在argsport属性中更改端口以匹配,就可以随意更改端口。

The key differences for me was making sure mocha was in node_modules, using programto point to the executable, and argsneeding debug-brk=xpointing to the port specified in port. The rest of the above just makes things prettier and easier.

对我来说,关键的区别是确保摩卡是node_modules,采用program以点到可执行文件,并且args需要debug-brk=x指向在指定的端口port。上面的其余部分只是让事情变得更漂亮和更容易。

It's up to you and your team if you put .vscode/launch.jsonin the repository or not. It's an IDE-only file, but your whole team could use it like this, no problem, since all paths and installs are relative and explicit.

是否放入.vscode/launch.json存储库取决于您和您的团队。这是一个仅限 IDE 的文件,但您的整个团队都可以这样使用它,没问题,因为所有路径和安装都是相对且显式的。

Tip: The package.jsoncan include a scriptstag that also launches mocha with something like "test": "./node_modules/.bin/mocha", but it is not used by VS Code—instead it is used when npm testis run at the command line. This one confused me for a bit. Noting it here in case others get confused too.

提示:package.json可以包含一个scripts标签,该标签也可以使用类似的东西启动 mocha "test": "./node_modules/.bin/mocha",但 VS Code 不使用它——而是npm test在命令行运行时使用它。这让我有点困惑。在这里注意以防其他人也感到困惑。

EDIT: VS Code 1.9.0 has added an "Add Configuration" option in the debug configuration drop-down, and you can pick "Node.js Mocha Tests" which help simplify most of the above. You still need to make sure mocha is in your node_modulesand might have to update the cwdand last runtimeArgs(which is the pattern for finding your tests) to point to the appropriate paths. But once you set those two properties, it should work pretty much from there.

编辑:VS Code 1.9.0 在调试配置下拉菜单中添加了“添加配置”选项,您可以选择“Node.js Mocha 测试”,这有助于简化上述大部分内容。您仍然需要确保 mocha 在您的目录中,node_modules并且可能需要更新cwd和 last runtimeArgs(这是查找测试的模式)以指向适当的路径。但是一旦你设置了这两个属性,它应该可以从那里开始工作。