VSCode 调试器无法连接到 Karma 的 puppeteer 实例 运行

VSCode debugger can not connect to puppeteer instance run by Karma

我用 Karma 和 Jasmine 进行了 Angular 前端测试 运行,我想用 Visual Studio 代码进行调试。测试是 运行 在 puppeteer 实例中。

我的karma.conf.js:

// Karma configuration file, see link for more information
// https://karma-runner.github.io/0.13/config/configuration-file.html

process.env.CHROME_BIN = require('puppeteer').executablePath();

module.exports = function(config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-spec-reporter'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma'),
    ],
    client: {
      clearContext: false, // leave Jasmine Spec Runner output visible in browser
    },
    mime: {
      'text/x-typescript': ['ts', 'tsx'],
    },
    coverageIstanbulReporter: {
      reports: ['html', 'lcovonly'],
      fixWebpackSourcePaths: true,
    },
    angularCli: {
      environment: 'dev',
    },
    reporters:
      config.angularCli && config.angularCli.codeCoverage
        ? ['progress', 'coverage-istanbul']
        : ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['ChromeHeadlessNoSandbox'],
    customLaunchers: {
      ChromeHeadlessNoSandbox: {
        base: 'ChromeHeadless',
        debug: true,
        flags: ['--no-sandbox', '--remote-debugging-port=9333'],
      },
    },
    browserNoActivityTimeout: 120000,
    singleRun: false,
  });
};

我launch.json的相关部分:

{
  "type": "chrome",
  "request": "attach",
  "name": "Debug Frontend Tests",
  "address": "localhost",
  "port": 9333,
  "sourceMaps": true,
  "webRoot": "${workspaceFolder}/client/web",
}

TL,DR:将标记 '--remote-debugging-address=0.0.0.0' 添加到 customLaunchers' flags 数组。

事实证明,添加 '--remote-debugging-port=9333' 标志仅为本地计算机上的客户端打开端口。由于 puppeteer 在 Docker 容器中运行,它会将 VSCode 视为远程客户端并拒绝连接。

运行 lsof -i -P -n | grep LISTEN 容器内部显示 Chrome 仅为本地客户端打开端口 9333:

root@b6ff203497dc:~# lsof -i -P -n | grep LISTEN 
node    247 root   21u  IPv4 224919      0t0  TCP *:9876 (LISTEN)
chrome  260 root  137u  IPv4 229390      0t0  TCP 127.0.0.1:9333 (LISTEN)

另外添加标志 '--remote-debugging-address=0.0.0.0' 使 Chrome 为所有 IP 地址打开端口。

root@b6ff203497dc:~# lsof -i -P -n | grep LISTEN 
node    247 root   21u  IPv4 224919      0t0  TCP *:9876 (LISTEN)
chrome  260 root  137u  IPv4 229390      0t0  TCP *:9333 (LISTEN)

现在VSCode可以连接了。

关键提示来自:

Chrome remote debugging from another machine

https://github.com/puppeteer/puppeteer/issues/5063#issuecomment-561595885