> ## Documentation Index
> Fetch the complete documentation index at: https://e2e.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Electron

> 使用 @e2e-dev/electron 对 Electron 应用进行端到端测试。

`@e2e-dev/electron` 会启动你的 Electron 应用并驱动其窗口。测试使用与其他所有平台相同的 `agent`、`screen` 和 `expect` API。

<Warning>
  **Electron 支持处于实验阶段**。其 API 和行为可能在任何版本（包括补丁版本）中发生变化。请将 `@e2e-dev/electron` 固定到精确版本，并在升级前阅读[发布说明](https://github.com/e2e-inc/e2e/releases)。
</Warning>

## 安装与配置

安装运行器、引擎和 Electron：

<CodeGroup>
```bash npm
npm install --save-dev e2e @e2e-dev/electron electron
```

```bash pnpm
pnpm add --save-dev e2e @e2e-dev/electron electron
```

```bash bun
bun add --dev e2e @e2e-dev/electron electron
```
</CodeGroup>

在尚未配置 e2e 的项目中，运行 `npx e2e init --yes --engine electron` 会自动生成配置文件和示例测试。运行 `npx e2e init my-app --example with-electron` 则会基于 [Electron 示例](https://github.com/e2e-inc/e2e/tree/main/examples/with-electron)创建一个新项目。

引擎会启动项目中安装的 `electron` 包。运行 `npx e2e doctor` 检查环境配置。

## 指向你的应用

将 `app.appPath` 设置为你的应用目录或主脚本。每次启动都会附带 `app.launchArguments` 中的开关参数。

```ts title="e2e.config.ts"

export default {
  targets: [
    {
      name: 'electron',
      engine: electron(),
      app: { appPath: '.', launchArguments: ['--no-update-check'] },
    },
  ],
  credentials: {
    ada: { username: 'ada', password: process.env.ADA_PASSWORD ?? '' },
  },
} satisfies E2EConfig;
```

其中的 `credentials` 块是下文登录测试使用的测试用户。详见[凭据](https://e2e.com/docs/zh/authentication#credentials)。

应用不会继承运行器的环境变量，因此模型密钥和 CI 令牌不会传入应用。如有应用需要的变量，请通过 `electron({ env })` 传入。参考文档列出了全部[选项](https://e2e.com/docs/zh/reference/electron#options)、[应用启动时带有的环境变量](https://e2e.com/docs/zh/reference/electron#environment)以及[引擎附加的启动参数](https://e2e.com/docs/zh/reference/electron#launch-arguments)。

## 编写测试

从 `@e2e-dev/electron` 导入 `test`。`app.open()` 会启动应用并等待一个窗口加载完成。每个测试都从空白的用户数据目录开始，并在测试结束时退出应用。调用 `app.restart()` 会在同一份数据上重启应用，调用 `app.clearState()` 则会在空白数据上重启。

```ts title="tests/sign-in.e2e.ts"

test('signs in and opens settings', async ({ app, screen, electron }) => {
  const ada = credentials.user('ada');
  await app.open();
  await screen.getByRole('textbox', 'Username').fill(ada.username);
  await screen.getByRole('textbox', 'Password').fill(ada.password);
  await screen.getByRole('button', 'Sign in').tap();
  await expect(screen.getByTestId('status')).toContainText('Signed in as ada');

  await electron.waitForWindow(() => screen.getByRole('button', 'Open settings').tap());
  await expect(screen.getByRole('heading', 'Settings')).toBeVisible();

  const userData = await electron.evaluate(({ app: main }) => main.getPath('userData'));
  expect(userData).toContain('e2e-electron-');
});
```

## electron 测试夹具

`electron` 测试夹具用于控制应用本身：启动、窗口、主进程、按键、对话框和下载。下文逐一演示各项用法。[Electron 引擎参考](https://e2e.com/docs/zh/reference/electron#the-electron-fixture)列出了每个成员的参数、默认值和错误码。

## 使用按测试定制的参数启动

`electron.launch()` 像 `app.open()` 一样启动应用，并在此测试的目标配置基础上附加启动参数和环境变量。`cwd` 用于设置进程启动的工作目录。`app.open()`、`app.restart()` 和 `app.clearState()` 会保留这些设置直到测试结束；再次调用 `launch()` 则会替换它们。

`electron.userDataDir` 在应用启动前就已存在，因此测试可以先往其中写入数据：

```ts

test('opens on saved settings', async ({ electron, screen }) => {
  writeFileSync(path.join(electron.userDataDir, 'settings.json'), '{"theme":"dark"}');
  await electron.launch({
    launchArguments: ['--skip-onboarding'],
    env: { APP_DATA_PATH: electron.userDataDir },
  });
  await expect(screen.getByRole('heading', 'Projects')).toBeVisible();
});
```

如果想在每个测试中都以这种方式启动，请在[测试夹具](https://e2e.com/docs/zh/fixtures)中调用 `electron.launch()`。

## 处理多个窗口

窗口的行为类似于[浏览器测试中的标签页](https://e2e.com/docs/zh/reference/web#tabs)。`screen` 只读取当前活动窗口，默认从第一个加载的窗口开始。应用自行打开的新窗口不会自动成为活动窗口：`electron.waitForWindow()` 会执行触发打开窗口的步骤，并将其设为活动窗口。当活动窗口关闭时，打开它的窗口会重新成为活动窗口，否则恢复为之前处于活动状态的窗口。

```ts
const settings = await electron.waitForWindow(() =>
  screen.getByRole('button', 'Open settings').tap(),
);
await expect(screen.getByRole('heading', 'Settings')).toBeVisible();

const [main] = electron.windows();
await main.activate();
await settings.close();
```

对于应用自行打开的窗口（例如启动画面之后出现的主窗口），可以用 `electron.window()` 查找：

```ts
const main = await electron.window({ title: 'My App' });
await main.activate();
```

`title` 和 `url` 接受精确字符串或 `RegExp`。智能体会将窗口视作标签页，并在需要时自行切换。全部窗口方法（包括 [`evaluate()`](#run-code-in-a-window)）请参阅[窗口与活动窗口](https://e2e.com/docs/zh/reference/electron#windows-and-the-active-window)。

## 在主进程中运行代码

对于无法从窗口访问的主进程 API（例如触发菜单项或替换原生对话框），请使用 `electron.evaluate()`：

```ts
// Trigger a menu item
await electron.evaluate(({ Menu }) => {
  Menu.getApplicationMenu()?.getMenuItemById('open-settings')?.click();
});

// Stub a native file dialog
await electron.evaluate(({ dialog }, filePath) => {
  dialog.showOpenDialog = async () => ({ canceled: false, filePaths: [filePath] });
}, '/tmp/report.csv');
```

`fn` 以文本形式发送，因此不能捕获测试中的闭包变量：请通过 `arg` 传入值（仅限纯 JSON，拒绝机密值），并返回纯数据。`fn` 内部作用域中没有 `require`；请使用 `electron` 参数或 `process.getBuiltinModule('node:fs')`。

## 在窗口中运行代码

`window.evaluate()` 在窗口页面中运行函数，可访问应用自身的全局变量。它遵循与 `electron.evaluate()` 相同的规则：`fn` 以文本形式发送，`arg` 和返回值都必须是纯 JSON。

```ts
const window = electron.activeWindow();
const theme = await window.evaluate((key) => localStorage.getItem(key), 'theme');
await window.reload();
```

## 在窗口上等待与断言

`expect(electron)` 对活动窗口执行断言并持续重试直到断言超时，与网页端的 [`expect(browser)`](https://e2e.com/docs/zh/reference/expect) 相同：

```ts
await expect(electron).toHaveURL(/\/settings$/);
await expect(electron).toHaveTitle('Settings');
await expect(electron).toHaveClass(screen.getByRole('row', 'Draft'), /selected/);
await expect(electron).not.toHaveTitle('Sign in');
```

- `toHaveURL` 和 `waitForURL` 接受绝对 URL 或 `RegExp`。Electron 应用没有基准 URL，因此不带协议头的字符串（例如 `'settings.html'` 或 `'**/settings'`）会报 `INVALID_ARGUMENT`。字符串不会被当作 glob：需要模式匹配时请使用 `RegExp`。
- `toHaveClass` 的第一个参数是定位器。传入字符串时匹配整个 class 列表。没有 `class` 属性的元素不会匹配任何字符串，包括 `''`。
- 每个匹配器都支持 `{ timeout }`，`toHaveURL` 还支持 `{ ignoreCase }`。

`electron.waitForURL()` 会将同样的等待作为独立步骤运行：

```ts
await electron.waitForURL(/\/workspace\/[^/]+\/debug$/);
```

对于页面的其他条件（例如计算样式），可以使用 [`expect.poll`](https://e2e.com/docs/zh/reference/expect#polling-a-value) 轮询 [`window.evaluate()`](#run-code-in-a-window)。

## 键盘与鼠标

`electron.keyboard` 和 `electron.mouse` 向活动窗口当前焦点或指针所在位置发送输入。如果有明确的元素可供定位，请优先使用 `locator.press()` 和 `locator.fill()`。

```ts
await electron.keyboard.press('Escape');
await electron.keyboard.press('ControlOrMeta+P');
await electron.keyboard.type('hello', { delay: 20 });
await electron.mouse.move(0, 0);
```

- `keyboard` 提供 `press`、`down`、`up`、`type` 和 `insertText`；`mouse` 提供 `move`、`down`、`up` 和 `wheel`。详见 [`keyboard`](https://e2e.com/docs/zh/reference/electron#keyboard) 和 [`mouse`](https://e2e.com/docs/zh/reference/electron#mouse)。
- 由页面处理的快捷键可以正常工作，菜单快捷键（menu accelerator）不会触发：详见[限制](#limits)。
- `type` 不接受机密值。请使用 `locator.fill()` 填写机密值。

## 处理 alert 和 confirm 对话框

`electron.onDialog()` 用于响应应用随后打开的对话框，用法与网页端的 [`browser.onDialog()`](https://e2e.com/docs/zh/reference/web#ondialog) 相同。传入 `'accept'`、`'dismiss'` 或一个处理函数，调用其返回的函数即可取消监听：

```ts
const off = await electron.onDialog('accept');
await screen.getByRole('button', 'Delete').tap();
await off();

await electron.onDialog(async (dialog) => {
  expect(dialog.message).toBe('Discard changes?');
  await dialog.dismiss();
});
```

处理函数必须调用 `accept()` 或 `dismiss()`。没有任何处理程序接管的对话框会被自动取消（`confirm()` 返回 `false`），并使测试的下一个步骤失败；如果是由最后一个步骤打开的，则会使该测试失败。

## 上传文件

`setInputFiles` 支持按路径（相对于项目根目录解析）或从内存附加文件。可在文件 `<input>` 或打开文件选择器的按钮上调用它，传入 `[]` 可清空输入。带有 `webkitdirectory` 的输入框只接受单个目录（不接受文件），并会附带该目录下的文件：

```ts
await screen.getByTestId('attachment').setInputFiles('fixtures/report.csv');
await screen.getByRole('button', 'Choose file').setInputFiles('fixtures/report.csv');
await screen.getByTestId('attachment').setInputFiles({
  name: 'note.txt',
  mimeType: 'text/plain',
  buffer: Buffer.from('written in the test'),
});
await screen.getByTestId('attachment').setInputFiles([]);
await screen.getByTestId('folder').setInputFiles('fixtures/photos');
```

## 下载

`electron.waitForDownload()` 运行触发下载的步骤并等待文件完成，随后将文件复制到测试产物中：

```ts
const file = await electron.waitForDownload(() => screen.getByRole('link', 'Export').tap());
expect(file.suggestedFilename).toBe('report.csv');
// file.absolutePath is the saved file
```

下载文件会保存到测试的用户数据目录中，而非你本机的 Downloads 文件夹，除非应用自行指定保存路径，或者下载在首个窗口加载前就已经开始。如果目标目录中已有同名文件，系统会自动编号，例如 `note (1).txt`（[详见参考](https://e2e.com/docs/zh/reference/electron#waitfordownload)）。

## 录制视频

使用 `--video on` 运行或在配置中设置 `video`，即可为每个测试录制视频。视频会跟随 `screen` 读取的窗口（跨 `app.restart()` 也一样），并以单个 `.webm` 文件保存在测试结果中。如果只需录制测试的一部分，可调用 `app.startRecording()` 和 `app.stopRecording()`。

视频编码需要 ffmpeg：引擎会先查找系统中的 ffmpeg，若未找到则在首次录制时自动下载。设置 `E2E_FFMPEG_PATH` 可指定你自己的 ffmpeg。

## 测试打包后的应用

要测试打包构建的应用，请将 `executablePath` 指向可执行文件（在 macOS 上不要指向 `.app` 目录），并省略 `app.appPath`：

```ts title="e2e.config.ts"
{
  name: 'electron-packaged',
  engine: electron({
    executablePath: 'dist/mac/MyApp.app/Contents/MacOS/MyApp',
  }),
}
```

在 Windows 上，请指定应用的 `.exe`，而不是目录或快捷方式：

```ts title="e2e.config.ts"
{
  name: 'electron-packaged',
  engine: electron({
    executablePath: 'dist/win-unpacked/MyApp.exe',
  }),
}
```

通过 Squirrel 安装程序（`electron-winstaller`，Electron Forge 的默认方式）安装的应用会在 `app-<version>` 目录旁边保留一个同名启动器。请指向版本目录里面的 `.exe`。

- 如果构建禁用了 `EnableNodeCliInspectArguments` fuse，`screen`、`expect` 和智能体仍能正常工作，但 `electron.evaluate()` 和 `electron.waitForDownload()` 会失败，且 `electron.window({ title })` 仅匹配文档标题。在 Windows 和 Linux 上，对应用调用 `hide()` 隐藏的窗口进行截图也会超时，且录制结果没有画面帧。
- 在 macOS 上，读取钥匙串（`safeStorage`）的未签名构建可能会卡在系统弹窗上。请在 `app.launchArguments` 中添加 `--use-mock-keychain`。

## 在 Linux CI 中运行

Electron 需要显示服务器才能打开窗口。在 Linux CI 中，请通过 `xvfb-run` 运行 e2e：

<CodeGroup>
```bash npm
xvfb-run --auto-servernum npx e2e run
```

```bash pnpm
xvfb-run --auto-servernum pnpm exec e2e run
```

```bash bun
xvfb-run --auto-servernum bunx e2e run
```
</CodeGroup>

引擎在 Linux 上会自动添加 `--no-sandbox`。

## 与网页端的差异

| 类别 | Electron 上的行为 |
| --- | --- |
| 查找元素 | 位于 `inert` 子树内的元素（例如模态框背后的页面）没有角色或标签：`getByRole` 和 `getByLabel` 找不到它。`getByText`、`getByTestId` 和 `electron.locator()` 可以找到它，但对其执行 `tap()` 或 `fill()` 等输入会以 `it is inert` 失败 |
| 启动参数 | 引擎会添加[自带的开关参数](https://e2e.com/docs/zh/reference/electron#launch-arguments)，例如 `--inspect=0` 和 `--user-data-dir=...`。严格的参数解析器必须允许它们 |
| 并行工作进程 | 每个测试都有独立的用户数据目录，因此测试可以并行运行。如果你的应用覆盖了 `app.setPath('userData', ...)`，请设置 `workers: 1` |
| 剪贴板 | 应用使用操作系统的剪贴板，因此测试中的复制会覆盖你的剪贴板。涉及剪贴板的测试请设置 `workers: 1` |
| 主题与语言区域 | `prefers-color-scheme` 跟随 `nativeTheme` 和操作系统。Chromium UI 文本跟随系统语言区域；在 `app.launchArguments` 中添加 `--lang=en-US` 可固定为英文 |
| 长按 | 默认按住 800 ms，而网页端为 500 ms |
| CSS 选择器 | `electron.locator()` 会在窗口文档和各个开放的 shadow root 中逐根查找，但不会进入 iframe |
| 渲染进程崩溃 | 窗口崩溃后，读取操作会持续失败，直到你使用 `electron.evaluate()` 重新加载该窗口或重启应用 |

完整列表请参阅 [Electron 上的行为](https://e2e.com/docs/zh/reference/electron#behavior-on-electron)。

## 安全

应用运行在隔离的环境变量中；密码字段不会被读取，且在截图中会被涂黑；导航到应用目录之外的本地文件时，该窗口不会被观察或截图。每次测试期间，主进程会监听一个未鉴权的回环端口供 `electron.evaluate()` 使用。详情请参阅[安全](https://e2e.com/docs/zh/reference/electron#security)。

## 限制

### Electron 本身不支持

- **`prompt()`**：Electron 未实现 `window.prompt()`，在页面中调用会抛出异常。
- **无头模式**：除非应用主动隐藏窗口，Electron 总是会打开窗口，`--headed` 不起作用。在 Linux CI 上请使用 `xvfb-run`。
- **菜单快捷键**：键盘事件会直接发送到页面，因此菜单快捷键和 `before-input-event` 不会收到它们。请使用 `electron.evaluate()` 触发菜单项。
- **超长页面**：单边超过 16384 图像像素的 `fullPage` 截图会被拒绝，因为超过该尺寸后 Chromium 会重复绘制页面顶部。请改用 `clip` 截取页面的局部区域。

### 暂不支持

- `iframe` 或 `webview` 内部的内容（`webview` 客体页会作为窗口列出，因此可以通过 `electron.window()` 访问）
- 路由拦截和 Cookie（请改在 `electron.evaluate()` 中使用 `session.defaultSession`）
- 会话保存与恢复
- 在测试中读取应用控制台输出

## 下一步

<CardGroup cols={2}>
  <Card title="Electron 引擎参考" icon="book" href="/reference/electron">
    每个选项和 `electron` 测试夹具成员的默认值与错误码。
  </Card>
  <Card title="智能体步骤" icon="robot" href="/agent-steps">
    让智能体填写表单或检查屏幕内容。
  </Card>
  <Card title="引擎" icon="gears" href="/engines">
    编写你自己的引擎。
  </Card>
</CardGroup>
