> ## 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

> Test an Electron app end to end with @e2e-dev/electron.

`@e2e-dev/electron` launches your Electron app and drives its windows. Tests
use the same `agent`, `screen`, and `expect` APIs as on every other platform.

<Warning>
  **Electron support is experimental.** Its API and behavior can change in any
  release, including a patch. Pin `@e2e-dev/electron` to an exact version and
  read the [release notes](https://github.com/e2e-inc/e2e/releases) before you
  upgrade.
</Warning>

## Set up

Install the runner, the engine, and 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>

In a project with no e2e config yet, `npx e2e init --yes --engine electron`
writes the config and an example test for you.
`npx e2e init my-app --example with-electron` starts a new project from the
[Electron example](https://github.com/e2e-inc/e2e/tree/main/examples/with-electron)
instead.

The engine launches the `electron` package installed in your project. Run
`npx e2e doctor` to check your setup.

## Point at your app

Set `app.appPath` to your app's directory or main script. Every launch gets
the switches in `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;
```

The `credentials` block is the test user for the sign-in test below. See
[Credentials](https://e2e.com/docs/authentication#credentials).

The app doesn't inherit the runner's environment, so model keys and CI tokens
stay out of it. Pass anything your app needs with `electron({ env })`. The
reference lists every [option](https://e2e.com/docs/reference/electron#options), the
[variables the app starts with](https://e2e.com/docs/reference/electron#environment), and the
[switches the engine adds](https://e2e.com/docs/reference/electron#launch-arguments).

## Write a test

Import `test` from `@e2e-dev/electron`. `app.open()` launches the app and
waits for a window to load. Every test starts with an empty user-data
directory and quits the app when it ends. Call `app.restart()` to relaunch on
the same data, or `app.clearState()` to relaunch on empty data.

```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-');
});
```

## The electron fixture

The `electron` fixture controls the app itself: its launch, windows, main
process, keys, dialogs, and downloads. The sections below show each one. The
[Electron engine reference](https://e2e.com/docs/reference/electron#the-electron-fixture) lists
every member with its parameters, defaults, and errors.

## Launch with per-test arguments

`electron.launch()` launches the app as `app.open()` does, and adds arguments
and environment variables for this test to the target's. `cwd` sets the
directory the process starts in. `app.open()`, `app.restart()`, and
`app.clearState()` keep them until the test ends. Another `launch()` replaces
them.

`electron.userDataDir` exists before the app is launched, so a test can put
data in it first:

```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();
});
```

To launch this way in every test, call `electron.launch()` from a
[fixture](https://e2e.com/docs/fixtures).

## Work with several windows

Windows work like [tabs in a browser test](https://e2e.com/docs/reference/web#tabs). `screen` reads one
active window, starting with the first that loads. A window the app opens
doesn't become active on its own: `electron.waitForWindow()` runs the step
that opens it and makes it active. When the active window closes, the window
that opened it is active again, or else the one active before it.

```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();
```

For a window the app opens by itself, such as the main window after a splash
screen, find it with `electron.window()`:

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

`title` and `url` take an exact string or a `RegExp`. The agent sees windows
as tabs and switches between them on its own. See
[Windows and the active window](https://e2e.com/docs/reference/electron#windows-and-the-active-window)
for every window method, including [`evaluate()`](#run-code-in-a-window).

## Run code in the main process

Use `electron.evaluate()` for main-process APIs that aren't reachable from a
window, such as triggering a menu item or stubbing a native dialog:

```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` is sent as text, so it can't close over variables from the test: pass
values as `arg` (plain JSON only; secrets are refused) and return plain data.
`require` isn't in scope inside `fn`; use the `electron` argument or
`process.getBuiltinModule('node:fs')`.

## Run code in a window

`window.evaluate()` runs a function in the window's page, where the app's own
globals are. It follows the same rules as `electron.evaluate()`: `fn` is sent
as text, and `arg` and the result are plain JSON.

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

## Wait and assert on the window

`expect(electron)` asserts on the active window and retries until the
assertion timeout, as [`expect(browser)`](https://e2e.com/docs/reference/expect) does on the web:

```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` and `waitForURL` take an absolute URL or a `RegExp`. An Electron
  app has no base URL, so a string with no scheme, such as `'settings.html'`
  or `'**/settings'`, is `INVALID_ARGUMENT`. A string is never a glob: use a
  `RegExp` for a pattern.
- `toHaveClass` takes the locator first. A string is the whole class list. An
  element with no `class` attribute matches no string, `''` included.
- Every matcher takes `{ timeout }`, and `toHaveURL` also `{ ignoreCase }`.

`electron.waitForURL()` runs the same wait as a step of its own:

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

For any other condition of the page, such as a computed style, poll
[`window.evaluate()`](#run-code-in-a-window) with
[`expect.poll`](https://e2e.com/docs/reference/expect#polling-a-value).

## Keyboard and mouse

`electron.keyboard` and `electron.mouse` send input to the active window,
wherever its focus and pointer are. Prefer `locator.press()` and
`locator.fill()` when there is an element to name.

```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` has `press`, `down`, `up`, `type`, and `insertText`. `mouse` has
  `move`, `down`, `up`, and `wheel`. See
  [`keyboard`](https://e2e.com/docs/reference/electron#keyboard) and
  [`mouse`](https://e2e.com/docs/reference/electron#mouse).
- A shortcut the page handles works. A menu accelerator doesn't: see
  [Limits](#limits).
- `type` never takes a secret. Fill one with `locator.fill()`.

## Handle alert and confirm dialogs

`electron.onDialog()` answers the dialogs the app opens from then on, the
same way [`browser.onDialog()`](https://e2e.com/docs/reference/web#ondialog) does on the web. Pass
`'accept'`, `'dismiss'`, or a function, and call what it returns to stop:

```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();
});
```

A function handler must call `accept()` or `dismiss()`. A dialog no handler
takes is dismissed (`confirm()` returns `false`) and fails the test's next
step, or the test when its last step opened it.

## Upload files

`setInputFiles` attaches files by path, resolved from the project root, or
from memory. Call it on a file `<input>` or on a button that opens a file
chooser, and pass `[]` to clear an input:

```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([]);
```

## Downloads

`electron.waitForDownload()` runs the step that starts a download and waits
for the file. It is copied into the test's artifacts:

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

Downloads go inside the test's user-data directory, not your own Downloads
folder, unless the app picks the path itself or the download starts before its
first window loads. A name already taken there gets a number, as
`note (1).txt` ([details](https://e2e.com/docs/reference/electron#waitfordownload)).

## Record video

Run with `--video on`, or set `video` in the config, to record every test.
The video follows the window `screen` reads, through `app.restart()` too, and
is saved as one `.webm` with the test's results. To record part of a test,
call `app.startRecording()` and `app.stopRecording()`.

Encoding needs ffmpeg: the engine finds one, or downloads it on the first
recording. Set `E2E_FFMPEG_PATH` to use your own.

## Test a packaged app

To test a packaged build, point `executablePath` at the binary (not the
`.app` directory on macOS) and omit `app.appPath`:

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

On Windows, name the app's `.exe`, not its folder or a shortcut:

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

An app installed by a Squirrel installer (`electron-winstaller`, Electron
Forge's default) keeps a launcher of the same name beside its `app-<version>`
folders. Name the `.exe` inside the version folder.

- If the build disables the `EnableNodeCliInspectArguments` fuse, `screen`,
  `expect`, and the agent still work, but `electron.evaluate()` and
  `electron.waitForDownload()` fail and `electron.window({ title })` matches
  document titles only. On Windows and
  Linux, a screenshot of a window the app hid with `hide()` also times out,
  and a recording of one has no frames.
- On macOS, an unsigned build that reads the keychain (`safeStorage`) can
  hang on a system prompt. Add `--use-mock-keychain` to `app.launchArguments`.

## Run in CI on Linux

Electron needs a display server to open windows. On Linux CI, run e2e under
`xvfb-run`:

<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>

The engine adds `--no-sandbox` on Linux automatically.

## What differs from the web

| Area | On Electron |
| --- | --- |
| Finding elements | An element inside an `inert` subtree, such as the page behind a modal, has no role or label: `getByRole` and `getByLabel` don't find it. `getByText`, `getByTestId`, and `electron.locator()` do, and input to it, such as `tap()` or `fill()`, fails with `it is inert` |
| Launch arguments | The engine adds [switches of its own](https://e2e.com/docs/reference/electron#launch-arguments), such as `--inspect=0` and `--user-data-dir=...`. Strict argument parsers must allow them |
| Parallel workers | Each test gets its own user-data directory, so tests run in parallel. If your app overrides `app.setPath('userData', ...)`, set `workers: 1` |
| Clipboard | The app uses your OS clipboard, so a test's copy overwrites yours. Set `workers: 1` for clipboard tests |
| Theme and locale | `prefers-color-scheme` follows `nativeTheme` and the OS. Chromium UI strings follow the OS locale; add `--lang=en-US` to `app.launchArguments` to pin English |
| Long press | Holds for 800 ms by default, compared to 500 ms on the web |
| CSS selectors | `electron.locator()` searches the window document and open shadow roots one root at a time, and never enters frames |
| Crashed renderers | A crashed window fails reads until you reload it with `electron.evaluate()` or restart the app |

[Behavior on Electron](https://e2e.com/docs/reference/electron#behavior-on-electron) has the full
list.

## Security

The app runs in an isolated environment, password fields are never read and
are painted black in screenshots, and a window that leaves your app's
directory for another local file is not observed or captured. During each
test the main process listens on an unauthenticated loopback port for
`electron.evaluate()`. See [Security](https://e2e.com/docs/reference/electron#security) for the
details.

## Limits

### Not on Electron

- **`prompt()`:** Electron doesn't implement `window.prompt()` and throws in
  the page.
- **Headless mode:** Electron always opens windows unless your app hides
  them, and `--headed` has no effect. Use `xvfb-run` on Linux CI.
- **Menu accelerators:** keyboard events go straight to the page, so menu
  shortcuts and `before-input-event` don't receive them. Trigger menu items
  with `electron.evaluate()`.

### Not supported yet

- Content inside an `iframe` or `webview` (a `webview` guest is listed as a window, so `electron.window()` reaches it)
- Routes and cookies (use `session.defaultSession` in `electron.evaluate()` instead)
- Session save and restore
- Reading the app's console from a test

## Next

<CardGroup cols={2}>
  <Card title="Electron engine reference" icon="book" href="/reference/electron">
    Every option and `electron` fixture member, with defaults and errors.
  </Card>
  <Card title="Agent steps" icon="robot" href="/agent-steps">
    Let the agent fill a form or check the screen.
  </Card>
  <Card title="Engines" icon="gears" href="/engines">
    Write an engine of your own.
  </Card>
</CardGroup>
