You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在VS Code扩展测试中截图?(Ubuntu、@vscode/test-electron无头模式)

解决Ubuntu下无头VS Code扩展测试的截图问题

问题根源

@vscode/test-electron的无头模式不会创建真实的X11显示会话,而screenshot-desktop依赖系统显示服务捕获屏幕,这就是截图失败的核心原因。

解决方案步骤

1. 安装虚拟显示服务

Ubuntu下安装Xvfb(虚拟帧缓冲X服务器),为无头实例提供虚拟显示:

sudo apt-get install xvfb

2. 在测试脚本中启动虚拟显示

修改测试启动脚本(如runTest.js),先启动Xvfb并指定环境变量,让VS Code测试使用该虚拟显示:

const { spawn } = require('child_process');
const { runTests } = require('@vscode/test-electron');
const path = require('path');

// 启动Xvfb,创建1920x1080分辨率的虚拟显示
const xvfb = spawn('Xvfb', [' :99', '-screen', '0', '1920x1080x24']);

// 设置环境变量,让Electron实例绑定到虚拟显示
process.env.DISPLAY = ':99';

async function main() {
  try {
    await runTests({
      extensionDevelopmentPath: __dirname,
      extensionTestsPath: path.join(__dirname, './out/test/suite/index'),
      launchArgs: ['--headless', '--disable-gpu']
    });
  } catch (err) {
    console.error('测试运行失败:', err);
    xvfb.kill();
    process.exit(1);
  } finally {
    xvfb.kill();
  }
}

main();

3. 调整screenshot-desktop配置

在截图代码中明确指定X11捕获模式,避免自动检测错误:

const screenshot = require('screenshot-desktop');
const fs = require('fs');

async function takeScreenshot() {
  try {
    const imgBuffer = await screenshot({ format: 'png', screen: '0', x11: true });
    fs.writeFileSync('./test-screenshot.png', imgBuffer);
  } catch (err) {
    console.error('截图失败:', err);
  }
}

4. 验证权限

确保测试进程能访问虚拟显示,可临时执行:

xhost +local:root

测试完成后记得收回权限:

xhost -local:root

替代方案:使用Electron内置API

如果screenshot-desktop仍有问题,可直接用Electron的窗口捕获API,无需依赖系统显示服务:

const vscode = require('vscode');
const fs = require('fs');

async function captureVSCodeWindow() {
  const activeWindow = vscode.window.visibleTextEditors[0]?.window || vscode.window.activeTextEditor?.window;
  if (activeWindow) {
    // 获取VS Code窗口对应的Electron BrowserWindow实例
    const browserWindow = activeWindow['_window'];
    const image = await browserWindow.capturePage();
    fs.writeFileSync('./vscode-screenshot.png', image.toPNG());
  }
}

内容的提问来源于stack exchange,提问作者Ziv Shapira

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 15:09:57