Electron 调试与测试
核对 Electron 主进程与渲染进程断点调试、分级日志记录、框架 DevTools 集成、单元测试与端到端测试(含 Spectron 历史迁移至 Playwright)及 CI/CD 流水线。
学完这一章,你能够
- 核对 Electron 主进程与渲染进程断点调试、分级日志记录、框架 DevTools 集成、单元测试与端到端测试(含 Spectron 历史迁移至 Playwright)及 CI/CD 流水线。
调试主进程:Inspector、VS Code 与日志
Electron 同时包含主进程与渲染进程两套运行环境,需要分别配置调试通道。主进程基于 Node.js,可使用 `--inspect` 或 `--inspect-brk` 启动(如 `electron --inspect=9222 .`),再在 Chrome 打开 `chrome://inspect` 附加断点、查看调用栈与求值;在 VS Code 中配置 `launch.json`(`type: "node"`、`protocol: "inspector"`、`sourceMaps: true` 及 Windows 下 `electron.cmd`)即可直接对主进程逻辑与 IPC 设断点。本站离线实测(`inspector_and_vscode_launch_config`)核验了主进程端口 `9222` 与渲染进程远程端口 `9223` 分离及 `launch.json` 关键字段。
除交互断点外,主进程运行轨迹通常使用 `console.log` 或 `winston` 等日志库持久化,并按 `info`、`warn`、`error` 分级记录便于生产排障。本站离线实测(`structured_logger_levels`)在临时目录写入并回读 JSON 结构化日志,确认三类级别各 1 条且末条错误准确记录为 `file-read-failed`。
调试渲染进程与前端框架 DevTools
渲染进程调试可直接调用 `mainWindow.webContents.openDevTools()` 打开内置开发者工具检查 DOM、脚本、网络与性能(生产构建应按环境关闭);若需跨窗口或跨设备联调,则使用 `electron --remote-debugging-port=9223 .` 开放远程调试端口。使用 React 或 Vue 开发界面时,可安装 `electron-devtools-installer` 并在 `app.whenReady()` 中加载 `REACT_DEVELOPER_TOOLS` 等扩展以检视组件状态、Props 与事件。本站离线实测(`renderer_devtools_and_extension_contract`)核对了开发/生产环境 DevTools 开关策略及 React/Vue 两类扩展配置。
自动化测试、历史工具迁移与 CI/CD 集成
自动化测试分为单元测试与端到端(E2E)测试两层:单元测试可使用 Jest、Mocha + Chai 或 Node.js 内置断言验证主进程纯业务逻辑与渲染模块;端到端测试覆盖应用启动、窗口数量断言、按钮点击与 IPC 交互。需要特别说明历史演进:Spectron 曾是 Electron 官方基于 WebDriver 的 E2E 框架(配合 Mocha/Chai 启动 `Application` 校验 `getWindowCount()` 为 `1`),现已官方停止维护,新项目推荐迁移至 `Playwright + Electron` 或 WebdriverIO。结合 GitHub Actions / GitLab CI 自动完成依赖安装、单元与 E2E 执行及覆盖率上报,即可形成稳定的调试与质量闭环。本站离线实测(`unit_e2e_and_ci_test_runner`)运行 3 组 `node:assert/strict` 真实单元测试全部通过,并核验 E2E 窗口契约与 4 阶段 CI 流水线。
离线实测调试端口与 launch.json 校验、分级日志落盘、DevTools 开关策略及 node:assert 单元测试
展开查看收起
import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
function caseInspectorAndVscodeLaunchConfig() {
const launchConfig = {
type: 'node',
request: 'launch',
name: 'Electron Main',
program: '${workspaceFolder}/node_modules/electron/cli.js',
args: ['.'],
runtimeExecutable: null,
windows: { runtimeExecutable: '${workspaceFolder}/node_modules/.bin/electron.cmd' },
sourceMaps: true,
protocol: 'inspector',
};
const mainFlag = '--inspect=9222';
const rendererFlag = '--remote-debugging-port=9223';
const mainPort = Number(mainFlag.split('=')[1]);
const rendererPort = Number(rendererFlag.split('=')[1]);
const actual = {
mainPort,
rendererPort,
portsDistinct: mainPort !== rendererPort,
launchType: launchConfig.type,
protocol: launchConfig.protocol,
sourceMaps: launchConfig.sourceMaps,
hasWindowsExecutable: launchConfig.windows.runtimeExecutable.endsWith('electron.cmd'),
};
const expected = {
mainPort: 9222,
rendererPort: 9223,
portsDistinct: true,
launchType: 'node',
protocol: 'inspector',
sourceMaps: true,
hasWindowsExecutable: true,
};
return { name: 'inspector_and_vscode_launch_config', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
}
async function caseStructuredLoggerLevels() {
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'electron-debug-'));
try {
const logFile = path.join(tmpDir, 'main.log');
const levels = { info: 1, warn: 2, error: 3 };
const entries = [];
const log = (level, msg) => {
if (levels[level] >= levels.info) {
entries.push({ level, msg });
}
};
log('info', 'app-ready');
log('warn', 'slow-ipc-call');
log('error', 'file-read-failed');
const lines = entries.map((e) => JSON.stringify(e)).join('\n') + '\n';
await fs.writeFile(logFile, lines, 'utf8');
const persisted = (await fs.readFile(logFile, 'utf8')).trim().split('\n').map((l) => JSON.parse(l));
const counts = {
info: persisted.filter((e) => e.level === 'info').length,
warn: persisted.filter((e) => e.level === 'warn').length,
error: persisted.filter((e) => e.level === 'error').length,
};
const actual = { totalEntries: persisted.length, counts, lastError: persisted[2].msg };
const expected = { totalEntries: 3, counts: { info: 1, warn: 1, error: 1 }, lastError: 'file-read-failed' };
return { name: 'structured_logger_levels', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
} finally {
await fs.rm(tmpDir, { recursive: true, force: true });
}
}
function caseRendererDevtoolsAndExtensionContract() {
const shouldOpenDevTools = (env) => env === 'development';
const extensions = [
{ id: 'REACT_DEVELOPER_TOOLS', framework: 'React', installer: 'electron-devtools-installer' },
{ id: 'VUEJS_DEVTOOLS', framework: 'Vue', installer: 'electron-devtools-installer' },
];
const actual = {
openInDev: shouldOpenDevTools('development'),
openInProd: shouldOpenDevTools('production'),
extensionCount: extensions.length,
frameworks: extensions.map((e) => e.framework),
};
const expected = {
openInDev: true,
openInProd: false,
extensionCount: 2,
frameworks: ['React', 'Vue'],
};
return { name: 'renderer_devtools_and_extension_contract', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
}
function caseUnitE2eAndCiTestRunner() {
// Real node:assert/strict unit tests for main-process IPC note validator
const normalizeTitle = (raw) => String(raw ?? '').trim().slice(0, 40);
const unitResults = [];
const runTest = (name, fn) => {
fn();
unitResults.push({ name, ok: true });
};
runTest('trims_whitespace', () => assert.equal(normalizeTitle(' Electron Notes '), 'Electron Notes'));
runTest('clamps_length', () => assert.equal(normalizeTitle('x'.repeat(60)).length, 40));
runTest('handles_null', () => assert.equal(normalizeTitle(null), ''));
const e2eContract = {
windowCountExpected: 1,
legacyTool: 'spectron',
recommendedModernTool: 'playwright',
};
const ciStages = ['install-node-electron', 'unit-tests', 'e2e-tests', 'upload-coverage'];
const actual = {
unitPassed: unitResults.filter((r) => r.ok).length,
e2eWindowCount: e2eContract.windowCountExpected,
modernE2eTool: e2eContract.recommendedModernTool,
ciStagesCount: ciStages.length,
};
const expected = {
unitPassed: 3,
e2eWindowCount: 1,
modernE2eTool: 'playwright',
ciStagesCount: 4,
};
return { name: 'unit_e2e_and_ci_test_runner', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
}
const cases = [
caseInspectorAndVscodeLaunchConfig(),
await caseStructuredLoggerLevels(),
caseRendererDevtoolsAndExtensionContract(),
caseUnitE2eAndCiTestRunner(),
];
console.log(JSON.stringify({ version: process.version, cases }));
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
主进程运行在 Node.js V8 中,使用 --inspect 暴露 Node Inspector 协议;渲染进程运行在 Chromium 中,使用 webContents.openDevTools() 或 --remote-debugging-port 调试。由于 Spectron 已归档停止维护,新项目应使用 Playwright 的 _electron.launch 或 WebdriverIO 执行跨平台 E2E 测试。