Mocha 断点使用 Visual Studio 代码

Mocha breakpoints using Visual Studio Code

是否可以使用 Visual Studio 代码为 Mocha 测试添加断点?

一般在调试代码时,需要配置launch.json,将程序属性设置为Javascript文件才能执行。不过,我不确定如何为 Mocha 执行此操作。

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

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

    {
        "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

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

另一种方法是使用 mocha 的 --debug-brk 命令行选项和 Visual Studio 代码调试器的默认 Attach 启动设置。


建议更深入的解释(来自 André)

为此:

运行 从命令行使用此命令的 mocha:

mocha --debug-brk

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

我在 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"}
        }
    ]
}

它也可以作为要点 here

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

对于使用 Windows 的任何人。如果你已经全局安装了 mocha,那么将程序设置为以下路径对我有用(交换你的用户名)。

"program": "C:\Users\myname\AppData\Roaming\npm\node_modules\mocha\bin\_mocha"

使用 TypeScript 时,以下配置适用于 Visual Studio Code 0.8.0 (tsc 1.5.3)

tsconfig.json

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "noImplicitAny": false,
        "removeComments": true,
        "preserveConstEnums": true,
        "sourceMap": true,
        "outDir": "build",
        "declaration": false
    },
    "files": [
        "./src/index.ts",
        "./src/test/appTests.ts"
    ]
}

这里需要注意的重要事项是源映射已生成并且 js 的输出目录设置为 build

launch.json

    {
        "name": "Attach",
        "type": "node",
        // TCP/IP address. Default is "localhost".
        "address": "localhost",
        // Port to attach to.
        "port": 5858,
        "sourceMaps": true,
        "outDir": "build"
    }

请注意 sourceMaps 设置为 true 并且 outDir 设置为 build

调试

  1. index.ts 任何其他导入的打字稿文件中设置断点
  2. 打开一个终端然后运行:mocha --debug-brk ./build/test/appTests.js
  3. 从 VSC,运行 'Attach' 启动配置

如果您不想使用 --debug-brk+附加或声明您的全局 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"
  }
}

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

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

我在 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 需要安装在 npm 模块目录中。

这是 Microsoft 的 launch configuration (launch.json) 示例,它与 Mocha 一起使用并允许使用调试器。

此外,还有一个 description 如何使用 --debug-brk 选项。

最后,这是一个 alternative version of how to debug code with Mocha tests 使用 VS Code 的 tasks.json 文件和 Gulp 任务运行器。

很抱歉添加另一个答案,但是从 VS Code 1.8.1 开始,none 之前的答案对我来说非常有用,其中包含标准的 Node 调试器。这是我解决它的方法(根据这里以前的答案和官方 VS Code Node.js Debugging 文档的指导)所以有一个 click/keypress 调试:

  • 确保 mocha 在 packages.json 中作为 devDependency 安装:"devDependencies": { "mocha": "^3.2", ... }
  • 运行 npm installpackage.json 的目录中,以确保 mocha 现在安装在 node_modules/
  • 打开 .vscode/launch.json(或在 VS Code 中,按 F1,开始键入 "launch",然后 select "Debug: Open launch.json")
  • 单击右下角的蓝色 "Add Configuration" 按钮(或复制并粘贴其他按钮);此步骤是可选的...我的意思是,您可以 re-use 现有配置。但我建议添加一个以减少混淆。
  • 更改 launch.json 中的以下内容,然后在 VS Code 的调试 window 中选择新的配置名称,然后单击绿色箭头开始调试节点 + mocha 测试!

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
}, ...]

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

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

我的主要区别是确保 mocha 在 node_modules 中,使用 program 指向可执行文件,而 args 需要 debug-brk=x 指向端口在 port 中指定。上面的其余部分只会让事情变得更漂亮、更容易。

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

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

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

我在 Windows 7 机器上工作。我确实在全球范围内安装了 mocha,但此配置指向项目安装以避免需要用户配置文件路径(顺便说一句,我尝试使用 %USERPROFILE% 变量但没有成功)。我现在可以在我的 mocha 测试中设置断点了。耶!

{
        "name": "Mocha Tests",
        "type": "node",
        "request": "launch",
        "stopOnEntry": false,
        "program": "${workspaceRoot}/node_modules/mocha/bin/_mocha",
        "cwd": "${workspaceRoot}",
        "args": ["./test/**/*.js"],
        "runtimeExecutable": null,
        "envFile": "${workspaceRoot}/.env"
    }

对于那些使用 grunt 或 gulp 的人来说,配置非常简单。

Launch.json

{
"version": "0.2.0",
"configurations": [

    {
        "name": "Run mocha by grunt",
        "type": "node",
        "program": "${workspaceRoot}/node_modules/grunt/bin/grunt",
        "stopOnEntry": false,
        "args": ["mochaTest"],
        "cwd": "${workspaceRoot}",
        "runtimeExecutable": null
    }
]}

Gruntfile.js

module.exports = function (grunt) {

grunt.initConfig({
    mochaTest: {
        test: {
            options: {
                reporter: 'spec'
            },
            src: ['test/**/*test.js']
        }
    }
});

grunt.loadNpmTasks('grunt-mocha-test');

grunt.registerTask('default', 'mochaTest');};

在 VSCode 版本 1.13.0 (macOS) 中,他们在配置 -> Mocha Tests 下内置了它。

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

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

自 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
    }
}

旁注:debug-brk is deprectated(对于至少拥有 Node >= 版本 8 的任何人)。

在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"
    },

如果您需要配置节点版本,只需像这样添加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"
    },

如果您在 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"
        }
  1. 转到 Debug > Add Configuration... 菜单
  2. SelectNode.js环境
  3. Select Mocha Tests 出现的 drop-down 列表中的选项
  4. 将测试文件的路径键入 args 属性
  5. 的最后一项
  6. 添加一个breakpoint
  7. 单击 Debug 图标
  8. Select Mocha Tests 作为配置
  9. 按下 Start debugging 按钮
  10. :-)

使用 Babel 或生成 javascript 文件但在源代码中放置断点时 - 您必须确保启用 sourceMaps 并定义 outFiles。这是对我有用的示例配置。

    {
        "name": "Mocha Test",
        "type": "node",
        "request": "launch",
        "program": "${workspaceRoot}/packages/api/node_modules/mocha/bin/_mocha",
        "cwd": "${workspaceRoot}/packages/api",
        "args": ["--colors", "--no-timeouts", "out/test"],
        "outFiles": ["${workspaceRoot}/packages/api/out/*"],
        "sourceMaps": true,
    },

注意 - 您需要修改 outFiles 以包含您可能想要添加断点的所有内容。在单一存储库和多个依赖项目中,这可能会更加乏味。

1) 转到

.vscode

然后

launch.json

文件

2)在launch.json中添加如下配置-

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Mocha Test",
            "cwd": "${workspaceRoot}",
            "runtimeExecutable": "${workspaceRoot}/*folder_path_containing_test*/node_modules/.bin/mocha",
            "windows": {
                "runtimeExecutable": "${workspaceRoot}/*folder_path_containing_test*/node_modules/.bin/mocha.cmd"
            },
            "runtimeArgs": [
                "--colors",
                "--recursive",
                "${workspaceRoot}/*folder_path_till_test*/tests"
            ],
            "internalConsoleOptions": "openOnSessionStart"
        },
        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "program": "${workspaceRoot}/*folder_path_to_test*/app.js"
        }
    ]
}

3) 在测试文件中设置断点,然后按F5

如果你在测试中有一些依赖,附加它也很容易。

例如,我正在使用 mongo-unit-helper 将单元测试与数据库集成。

package.json 脚本是:mocha --recursive --require ./test/mongo-unit-helper.js --exit"

我的 launch.json 看起来像:

  "configurations": [
  {
  "type": "node",
  "request": "launch",
  "name": "Mocha Tests",
  "program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
  "args": [
    "-u",
    "tdd",
    "--timeout",
    "999999",
    "--colors",
    "--recursive",
    "--require",
    "${workspaceFolder}/test/mongo-unit-helper.js",
    "${workspaceFolder}/test/**/*.js",
  ],
  "internalConsoleOptions": "openOnSessionStart"
 }
]

解决办法是把--require单独放在argslaunch.json.

最简单的解决方案

将以下代码添加到 .vscode 文件夹中的 launch.json 中:

{
            "name": "Unit tests",
            "type": "node",
            "request": "launch",
            "program": "${workspaceRoot}/node_modules/mocha/bin/_mocha",
            "args": [
            ],
        }

不过,您可能还想添加一个超时参数:

 {
            "name": "Unit tests",
            "type": "node",
            "request": "launch",
            "program": "${workspaceRoot}/node_modules/mocha/bin/_mocha",
            "args": [
                "--timeout",
                "999999"
            ],
        }

Github 上的官方 microsoft/vscode-recipes 有此 launch.json 用于调试 mocha 测试(输入 link 以获得更多 mocha 测试配置):

{
  "version": "0.2.0",
  "configurations": [
    {
        "type": "node",
        "request": "launch",
        "name": "Mocha All",
        "program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
        "args": [
            "--timeout",
            "999999",
            "--colors",
            "${workspaceFolder}/test"
        ],
        "console": "integratedTerminal",
        "internalConsoleOptions": "neverOpen",
        "skipFiles": [
            "<node_internals>/**/*.js"
        ]
    },
    {
        "type": "node",
        "request": "launch",
        "name": "Mocha Current File",
        "program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
        "args": [
            "--timeout",
            "999999",
            "--colors",
            "${file}"
        ],
        "console": "integratedTerminal",
        "internalConsoleOptions": "neverOpen",
        "skipFiles": [
            "<node_internals>/**/*.js"
        ]
    }
  ]
}