在 Visual Studio 代码中调试 Cypress 测试

Debugging Cypress tests in Visual Studio Code

我想使用 VS Code 来编辑和调试 Cypress 测试。 cypress 文档 mention VS Code directly,但不要提供任何有关如何配置 VS Code 的 launch.json 文件以在此处或在调试页面上进行调试的线索。

我有一个启动 cypress/electron 的 launch.json 配置,但 VS Code 给出了这个错误:

Cannot connect to runtime process… connect ECONNREFUSED 127.0.0.1:5858

然后关闭它。

查看 sample electron for VS Code project 没有帮助,添加 protocolprogram 属性也没有用。

这是我的配置:

{
    "name": "Start integration_tests",
    "type": "node",
    "request": "launch",
    "stopOnEntry": false,
    "cwd": "${workspaceRoot}",
    "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/cypress",
    "runtimeArgs": [
        "open"
    ],
    "console" : "internalConsole",
    "port": 5858,
}

我今天设置了这个并且成功了!

  1. 修改 plugins/index.js 以在调试模式下启动 Chrome (--remote-debugging-port=9222):
module.exports = (on, config) => {

  on('before:browser:launch', (browser = {}, args) => {

    if (browser.name === 'chrome') {
      args.push('--remote-debugging-port=9222')

      // whatever you return here becomes the new args
      return args
    }

  })
}

Cypress Browser Launch API

  1. 将以下内容添加到您的launch.json(注意与上面相同的端口)
{
  "type": "chrome",
  "request": "attach",
  "name": "Attach to Chrome",
  "port": 9222,
  "urlFilter": "http://localhost:4200/*",
  "webRoot": "${workspaceFolder}"
}
  1. 在测试中输入 "debugger" 这个词。参见 Cypress Doc on debugging
  2. 运行 "cypress open" 并从 Chrome
  3. 中的 #3 开始测试
  4. 使用新的 "Attach to Chrome" 配置启动 vscode 调试器
  5. 使用 "debugger" 重新启动测试并调试!

@fhilton 的回答曾经有效,但是对于较新版本的 Cypress,它会导致 Chrome 无法连接到测试 运行ner 而不是 运行 any测试。改用这个:

  1. 如果您或您的任何同事在 Windows、运行 npm i -D cross-env.

    中发展
  2. 在 package.json 中添加一个脚本来启动 Cypress 测试 运行ner(或者如果你已经有一个类似于 cypress open 的脚本,那么只需修改那)。您希望脚本在 运行s cypress open 之前将 CYPRESS_REMOTE_DEBUGGING_PORT 环境变量设置为类似 9222 的内容。由于我使用Windows,所以我使用cross-env npm包来设置环境变量。因此,我的 package.json 中的脚本看起来像

    "scripts": {
      "cypr": "cross-env CYPRESS_REMOTE_DEBUGGING_PORT=9222 cypress open",
    },
    

    我从 here and here 那里得到了这样做的想法。这个答案的其余部分主要是@fhilton 在他的答案中写的,所以大部分功劳归功于他们。

  3. 在你的launch.json中的configurations列表中添加以下内容(注意与上面相同的端口)

    {
        "type": "chrome",
        "request": "attach",
        "name": "Attach to Cypress Chrome",
        "port": 9222,
        "urlFilter": "http://localhost*",
        "webRoot": "${workspaceFolder}",
        "sourceMaps": true,
        "skipFiles": [
            "cypress_runner.js",
        ],
    },
    
  4. 把单词 debugger 放在你的测试中。参见 Cypress Doc on debugging。或者,如果您对自己的源映射有信心,请使用 vscode.

    在代码中放置一个断点
  5. 运行 npm run cypr(或者你给 npm 脚本起的任何名字)

  6. 来自 Cypress 测试 运行ner,开始你的测试 运行ning in Chrome

  7. 使用新的“附加到 Cypress Chrome”配置启动 vscode 调试器

  8. 重新启动带有断点的测试并调试!