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



我有使用 Karma 和 Jasmine 运行的 Angular 前端测试,我想用 Visual Studio Code 进行调试。测试在傀儡器实例中运行。

  • 当调试器尝试连接时,它会超时,并告诉我套接字已挂起。
  • 当我访问我的木偶实例正在侦听 http://localhost:9333/时,我得到一个ERR_EMPTY_RESPONSE
  • 将调试器连接到以chrome --headless --remote-debugging-port=9333开头的无头 Chrome 实例工作正常。

我的业力.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 远程调试

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

最新更新