diff --git a/.changeset/electron-per-test-launch.md b/.changeset/electron-per-test-launch.md
new file mode 100644
index 0000000000..e306d68224
--- /dev/null
+++ b/.changeset/electron-per-test-launch.md
@@ -0,0 +1,16 @@
+---
+'@e2e-dev/electron': patch
+---
+
+The `electron` fixture covers what a real app's suite needs beside `screen`:
+
+- `electron.launch({ args, env, cwd })` launches the app with arguments, environment variables, and a working directory of one test (`electron({ cwd })` sets the directory for every test), and `electron.userDataDir` is there before the launch, so a test can put data in it first. [Per-test arguments](https://e2e.com/docs/electron#launch-with-per-test-arguments)
+- `electron.keyboard` and `electron.mouse` send input to the active window, wherever its focus is: `await electron.keyboard.press('Escape')`. [Keyboard and mouse](https://e2e.com/docs/electron#keyboard-and-mouse)
+- `electron.activeWindow()` returns the window `screen` reads, and a window has `evaluate(fn, arg)`, which runs in its page, and `reload()`. [Run code in a window](https://e2e.com/docs/electron#run-code-in-a-window)
+
+Fixes:
+
+- A button drawn as an icon font's glyph and text, such as ``, is named `Scan`, as on the web. The glyph was part of its name, so `getByRole('button', 'Scan')` found nothing.
+- `getByText` on text in a container such as a toolbar, inside elements the accessibility tree leaves out, taps the text. It tapped the middle of the container, which could miss the element that handles the click.
+- A step that starts while the active window closes, such as a sign-in popup that closes itself, reads the window active after it instead of failing with `APP_NOT_OPEN`.
+- `locator.focus()` succeeds when the element hands focus to a part of itself, as a grid row does to its editor. It failed with `ACTION_FAILED`.
diff --git a/apps/electron-testbed/app/controls.html b/apps/electron-testbed/app/controls.html
index 4bba4f1f1a..5304f07c99 100644
--- a/apps/electron-testbed/app/controls.html
+++ b/apps/electron-testbed/app/controls.html
@@ -10,6 +10,7 @@
header { position: sticky; top: 0; height: 60px; background: #fff; border-bottom: 1px solid #ccc; z-index: 1; display: flex; align-items: center; padding: 0 24px; }
#cover { position: fixed; inset: 0; background: rgba(0, 0, 0, 0.2); }
.spacer { height: 900px; }
+ .glyph::before { content: '\f090'; }
@@ -95,6 +96,13 @@
Levels
+
+
Unselect All
+
+
+
Open row
+
+
Far below
diff --git a/apps/electron-testbed/app/controls.js b/apps/electron-testbed/app/controls.js
index 61f3d49ab6..2ff7d36974 100644
--- a/apps/electron-testbed/app/controls.js
+++ b/apps/electron-testbed/app/controls.js
@@ -110,3 +110,7 @@ const hostButton = document.createElement('button');
hostButton.textContent = 'Hosted action';
hostButton.addEventListener('click', () => count('host-clicks'));
document.querySelector('[data-testid="disabled-host"]').attachShadow({ mode: 'open' }).append(hostButton);
+document.querySelector('#unselect').addEventListener('click', () => count('unselect-clicks'));
+document.querySelector('#open-row').addEventListener('click', () => count('open-row-clicks'));
+const compositeRow = document.querySelector('[data-testid="composite-row"]');
+compositeRow.addEventListener('focus', () => compositeRow.querySelector('input').focus());
diff --git a/apps/electron-testbed/tests/controls.e2e.ts b/apps/electron-testbed/tests/controls.e2e.ts
index 0365432e24..ad2a24faeb 100644
--- a/apps/electron-testbed/tests/controls.e2e.ts
+++ b/apps/electron-testbed/tests/controls.e2e.ts
@@ -199,6 +199,28 @@ test.describe('controls page', () => {
await expect(screen.getByTestId('hold-state')).toHaveText('up', { timeout: 100 });
});
+ test('names a button by its text, not its icon font\'s glyph, as web() does', async ({ screen }) => {
+ await expect(screen.getByRole('button', 'Scan')).toBeVisible();
+ await expect(screen.getByTestId('glyph-button')).toHaveAccessibleName('Scan');
+ });
+
+ test('taps text where it is, not the middle of the container the tree folds it into', async ({ screen }) => {
+ await screen.getByText('Unselect All').tap();
+ await expect(screen.getByTestId('unselect-clicks')).toHaveText('1');
+ await screen.getByText('Open row').tap();
+ await expect(screen.getByTestId('open-row-clicks')).toHaveText('1');
+ // A control is its text wherever the text is drawn: the query answers with the button, and its state.
+ await expect(screen.getByText('Wide save')).toBeDisabled();
+ await expect(screen.getByText('Wide save')).toHaveRole('button');
+ });
+
+ test('focuses a composite that hands focus to a part of itself, and types there', async ({ screen }) => {
+ await screen.getByTestId('composite-row').focus();
+ await expect(screen.getByTestId('row-name')).toBeFocused();
+ await screen.getByTestId('composite-row').pressSequentially('abc');
+ await expect(screen.getByTestId('row-name')).toHaveValue('abc');
+ });
+
test('refuses a secret as electron.evaluate\'s argument', async ({ electron }) => {
const refused = await failure(electron.evaluate((_main, arg: unknown) => JSON.stringify(arg), { password: credentials.user('ada').password }));
expect(refused).toMatchObject({ code: 'POLICY_DENIED' });
diff --git a/apps/electron-testbed/tests/fixture.e2e.ts b/apps/electron-testbed/tests/fixture.e2e.ts
new file mode 100644
index 0000000000..7d9765b7d4
--- /dev/null
+++ b/apps/electron-testbed/tests/fixture.e2e.ts
@@ -0,0 +1,140 @@
+import { existsSync, writeFileSync } from 'node:fs';
+import path from 'node:path';
+import { test } from '@e2e-dev/electron';
+import { credentials, expect } from 'e2e';
+
+/** The page's document, as far as these tests read it: the project compiles without the DOM library. */
+interface PageGlobals {
+ readonly document: { readonly title: string; querySelector(selector: string): { readonly type: string } | null };
+}
+
+/** What a rejected step threw, for checking its code. */
+function failure(promise: Promise): Promise {
+ return promise.then(() => undefined, (error: unknown) => error);
+}
+
+test.describe('electron.launch', () => {
+ test('gives the test its data directory before the app runs, and launches on what it put there', async ({ electron }) => {
+ expect(existsSync(electron.userDataDir)).toBe(true);
+ writeFileSync(path.join(electron.userDataDir, 'seeded'), 'by the test');
+ await electron.launch();
+ const read = await electron.evaluate(({ app }) => {
+ const fs = process.getBuiltinModule('node:fs');
+ const file = process.getBuiltinModule('node:path').join(app.getPath('userData'), 'seeded');
+ return fs.readFileSync(file, 'utf8');
+ });
+ expect(read).toBe('by the test');
+ });
+
+ test('adds arguments and variables of the test\'s own, and keeps them through a restart', async ({ app, screen, electron }) => {
+ const launched = (): Promise<{ readonly args: readonly string[]; readonly mode: string | undefined }> =>
+ electron.evaluate(() => ({ args: process.argv.filter((argument) => argument.startsWith('--greeting=') || argument === '--per-test'), mode: process.env['TESTBED_MODE'] }));
+ await electron.launch({ args: ['--per-test'], env: { TESTBED_MODE: 'per-test' } });
+ await expect(screen.getByRole('heading', 'Hello from e2e')).toBeVisible();
+ // After the target's own arguments, and over the engine's `env`, which is still there.
+ expect(await launched()).toEqual({ args: ['--greeting=Hello from e2e', '--per-test'], mode: 'per-test' });
+ expect(await electron.evaluate(() => process.env['E2E_ELECTRON_HIDDEN'])).toBeDefined();
+ await app.restart();
+ expect(await launched()).toEqual({ args: ['--greeting=Hello from e2e', '--per-test'], mode: 'per-test' });
+ });
+
+ test('starts the app\'s process in the directory the test names', async ({ electron }) => {
+ await electron.launch({ cwd: 'app' });
+ expect(await electron.evaluate(() => process.cwd())).toMatch(/electron-testbed[\\/]app$/);
+ });
+
+ test('starts the next test without them', async ({ app, screen, electron }) => {
+ await app.open();
+ await expect(screen.getByRole('heading', 'Hello from e2e')).toBeVisible();
+ expect(await electron.evaluate(() => process.env['TESTBED_MODE'] ?? null)).toBeNull();
+ });
+
+ test('refuses an argument the engine owns, a variable it never sets, and an option it does not know', async ({ electron }) => {
+ expect(await failure(electron.launch({ args: ['--user-data-dir=/tmp/elsewhere'] }))).toMatchObject({ code: 'INVALID_ARGUMENT', message: expect.stringContaining('electron.launch({ args })') });
+ expect(await failure(electron.launch({ env: { TOKEN: credentials.user('ada').password as never } }))).toMatchObject({ code: 'POLICY_DENIED' });
+ expect(await failure(electron.launch({ env: { NODE_OPTIONS: '--inspect' } }))).toMatchObject({ code: 'INVALID_ARGUMENT' });
+ expect(await failure(electron.launch({ cwd: 'no-such-directory' }))).toMatchObject({ code: 'INVALID_ARGUMENT', message: expect.stringContaining('not a directory') });
+ expect(await failure(electron.launch({ headless: true } as never))).toMatchObject({ code: 'INVALID_ARGUMENT' });
+ });
+});
+
+test.describe('the app not running', () => {
+ test('has no active window to hand out', async ({ electron }) => {
+ let thrown: unknown;
+ try {
+ electron.activeWindow();
+ } catch (error) {
+ thrown = error;
+ }
+ expect(thrown).toMatchObject({ code: 'INVALID_STATE' });
+ });
+});
+
+test.describe('electron.keyboard and a window\'s page', () => {
+ test.beforeEach(async ({ app }) => {
+ await app.open();
+ });
+
+ test('types and presses into whatever holds focus, with a held modifier', async ({ screen, electron }) => {
+ const username = screen.getByRole('textbox', 'Username');
+ await username.focus();
+ await electron.keyboard.type('ada', { delay: 5 });
+ await expect(username).toHaveValue('ada');
+ await electron.keyboard.down('Shift');
+ await electron.keyboard.press('ArrowLeft');
+ await electron.keyboard.up('Shift');
+ await electron.keyboard.press('Backspace');
+ await expect(username).toHaveValue('ad');
+ await electron.keyboard.press('ControlOrMeta+A');
+ await electron.keyboard.insertText('grace');
+ await expect(username).toHaveValue('grace');
+ // A chord with a modifier the test holds leaves it held: the next arrow still selects.
+ await username.fill('ada');
+ await electron.keyboard.down('Shift');
+ await electron.keyboard.press('Shift+ArrowLeft');
+ await electron.keyboard.press('ArrowLeft');
+ await electron.keyboard.up('Shift');
+ await electron.keyboard.press('Backspace');
+ await expect(username).toHaveValue('a');
+ expect(await failure(electron.keyboard.down('NoSuchKey'))).toMatchObject({ code: 'UNSUPPORTED_CAPABILITY' });
+ expect(await failure(electron.keyboard.type(credentials.user('ada').password as never))).toMatchObject({ code: 'POLICY_DENIED' });
+ });
+
+ test('runs code in the active window\'s page, with its argument and its own error', async ({ electron }) => {
+ const window = electron.activeWindow();
+ expect(window.isActive()).toBe(true);
+ expect(await window.evaluate(() => (globalThis as unknown as PageGlobals).document.title)).toBe('Sign In');
+ expect(await window.evaluate((name: string) => (globalThis as unknown as PageGlobals).document.querySelector(`[name=${name}]`)?.type, 'password')).toBe('password');
+ expect(await window.evaluate(async () => await Promise.resolve({ nested: [1, 2] }))).toEqual({ nested: [1, 2] });
+ expect(await failure(window.evaluate(() => { throw new Error('from the page'); }))).toMatchObject({ code: 'EVALUATE_FAILED', message: expect.stringContaining('from the page') });
+ expect(await failure(window.evaluate((held: unknown) => held, { nested: [credentials.user('ada').password] }))).toMatchObject({ code: 'POLICY_DENIED' });
+ // What comes back is plain data, as from the main process: a bigint as its digits, a function left out.
+ expect(await window.evaluate(() => ({ big: 10n, run: () => 1, kept: 'yes' }))).toEqual({ big: '10', kept: 'yes' });
+ // The new document is there when reload() resolves: what the old one held is gone, with no wait.
+ await window.evaluate(() => {
+ (globalThis as { marked?: boolean }).marked = true;
+ });
+ await window.reload();
+ expect(await window.evaluate(() => (globalThis as { marked?: boolean }).marked ?? null)).toBeNull();
+ expect(await window.evaluate(() => (globalThis as unknown as { document: { readyState: string } }).document.readyState)).toBe('complete');
+ });
+
+ test('moves, presses, and scrolls with the mouse where the test points it', async ({ screen, electron }) => {
+ const box = await screen.getByRole('button', 'Add one').boundingBox();
+ if (box === null) throw new Error('the button has no box');
+ await electron.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
+ await electron.mouse.down();
+ await electron.mouse.up();
+ await expect(screen.getByTestId('count')).toHaveText('1');
+ // A right press is no click.
+ await electron.mouse.down({ button: 'right' });
+ await electron.mouse.up({ button: 'right' });
+ await expect(screen.getByTestId('count')).toHaveText('1');
+ const scrolled = (): Promise => electron.activeWindow().evaluate(() => (globalThis as unknown as { scrollY: number }).scrollY);
+ const before = await scrolled();
+ await electron.mouse.wheel(0, 200);
+ await expect.poll(scrolled).toBeGreaterThan(before);
+ expect(await failure(electron.mouse.move(Number.NaN, 0))).toMatchObject({ code: 'INVALID_ARGUMENT' });
+ expect(await failure(electron.mouse.down({ button: 'side' as never }))).toMatchObject({ code: 'INVALID_ARGUMENT' });
+ });
+});
diff --git a/docs/electron.mdx b/docs/electron.mdx
index a65b29fb14..8d124d8286 100644
--- a/docs/electron.mdx
+++ b/docs/electron.mdx
@@ -89,13 +89,45 @@ test('signs in and opens settings', async ({ app, screen, electron }) => {
| Method | What it does |
| --- | --- |
+| `launch({ args, env, cwd, timeout }?)` | Launches the app with [arguments and variables for this test](#launch-with-per-test-arguments) |
+| `userDataDir` | The test's user-data directory, which exists before the app is launched |
| `evaluate(fn, arg?)` | Runs `fn` in the main process with the `electron` module and returns its JSON-serializable result |
| `windows()` | The open windows, in the order they opened |
+| `activeWindow()` | The window `screen` reads |
| `waitForWindow(trigger, { timeout }?)` | Runs `trigger`, waits for the window it opens, and makes that window active |
| `window({ title, url }, { timeout }?)` | Waits for a window by title or URL and returns it, without making it active |
| `waitForDownload(trigger, { timeout }?)` | Runs `trigger` and waits for the [download](#downloads) it starts |
| `onDialog(handler)` | Answers the app's [`alert()` and `confirm()` dialogs](#handle-alert-and-confirm-dialogs) |
| `locator(selector)` | Queries the current window by CSS selector |
+| `keyboard`, `mouse` | [Keyboard and pointer input](#keyboard-and-mouse) for the active window |
+
+## 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
+import { writeFileSync } from 'node:fs';
+import path from 'node:path';
+
+test('opens on saved settings', async ({ electron, screen }) => {
+ writeFileSync(path.join(electron.userDataDir, 'settings.json'), '{"theme":"dark"}');
+ await electron.launch({
+ args: ['--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](/fixtures).
## Work with several windows
@@ -116,8 +148,8 @@ await main.activate();
await settings.close();
```
-A window has `title()`, `url()`, `isActive()`, `isClosed()`, `activate()`, and
-`close()`. For a window the app opens by itself, such as the main window after
+A window has `title()`, `url()`, `isActive()`, `isClosed()`, `activate()`,
+`close()`, `reload()`, and [`evaluate()`](#run-code-in-a-window). For a window the app opens by itself, such as the main window after
a splash screen, find it with `electron.window()`:
```ts
@@ -152,6 +184,37 @@ 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();
+```
+
+## 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`.
+- 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
@@ -259,6 +322,7 @@ The engine adds `--no-sandbox` on Linux automatically.
| Area | On Electron |
| --- | --- |
+| Finding elements | An element inside an `inert` subtree, such as the page behind a modal, is not in the tree: `getByRole`, `getByText`, and `getByLabel` don't find it, and `electron.locator()` does |
| Launch arguments | The engine adds `--inspect=0`, `--remote-debugging-pipe`, `--force-color-profile=srgb`, `--user-data-dir=...`, switches that keep a covered or hidden window drawing, and `--no-sandbox` on Linux. 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 |
@@ -300,7 +364,6 @@ The engine adds `--no-sandbox` on Linux automatically.
- 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
-- A `keyboard` fixture to hold a key down
- Reading the app's console from a test
## Options
@@ -308,6 +371,7 @@ The engine adds `--no-sandbox` on Linux automatically.
| Option | Type | Default | What it sets |
| --- | --- | --- | --- |
| `executablePath` | `string` | project's `electron` | Binary to start, such as a [packaged app](#test-a-packaged-app) |
+| `cwd` | `string` | project root | Directory the app's process starts in: absolute, or relative to the project root |
| `env` | `Record` | `{}` | Extra environment variables for the app (not `ELECTRON_RUN_AS_NODE` or `NODE_OPTIONS`); see [Security](#security) |
| `testIdAttribute` | `string` | `'data-testid'` | Attribute `getByTestId` reads |
| `settle` | `number \| false` | `100` | Wait time in milliseconds after an agent action before the next read (`false` skips it) |
diff --git a/docs/migrate/playwright.mdx b/docs/migrate/playwright.mdx
index d5e4341102..ce05887da3 100644
--- a/docs/migrate/playwright.mdx
+++ b/docs/migrate/playwright.mdx
@@ -421,13 +421,17 @@ config by hand.
| Playwright | e2e |
| --- | --- |
| `_electron.launch({ args })` in a fixture, `electronApp.firstWindow()` | `await app.open()` in `beforeEach`. Arguments the app reads, and Chromium switches, go in the target's `app.launchArguments`, the same for every test |
+| `_electron.launch({ args, env })` with values of one test, a data directory filled before the launch | `await electron.launch({ args, env })` and `electron.userDataDir`, see [per-test arguments](/electron#launch-with-per-test-arguments). The app doesn't inherit the runner's environment: name a variable it reads, such as `PLAYWRIGHT_TEST`, in `electron({ env })` |
| `electronApp.evaluate(fn, arg)` | `electron.evaluate(fn, arg)` |
-| `page.evaluate(fn)` in the renderer | `electron.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].webContents.executeJavaScript('…'))`. Pick the window by title: `getAllWindows()` is not in the order `electron.windows()` lists |
+| `page.evaluate(fn, arg)` in the renderer, `page.reload()`, `page.url()` | `electron.activeWindow().evaluate(fn, arg)`, `reload()`, `url()` |
+| `page.keyboard`, `page.mouse` | `electron.keyboard`, `electron.mouse` |
+| `page.waitForURL(re)`, `page.waitForFunction(fn)` | `await expect.poll(() => window.url()).toMatch(re)`, `await expect.poll(() => window.evaluate(fn)).toBeTruthy()` |
| `electronApp.waitForEvent('window')` | `await electron.waitForWindow(() => screen.getByRole('button', 'Open').tap())`, which makes the new window active. For a window the app opens on its own, `await electron.window({ title: 'Settings' })` |
| `page.on('dialog')` | `await electron.onDialog('accept')`, `'dismiss'`, or a handler |
| `page.waitForEvent('close')` | `await expect.poll(() => window.isClosed()).toBe(true)` |
| `expect(page).toHaveTitle(title)` | `await expect.poll(() => window.title()).toBe(title)` |
-| `page.getByRole`, `getByLabel`, `getByTestId`, `locator(css)` | `screen.getByRole`, `getByLabel`, `getByTestId`, and `electron.locator(css)`, which takes CSS only |
+| `page.getByRole`, `getByLabel`, `getByTestId`, `locator(css)` | `screen.getByRole`, `getByLabel`, `getByTestId`, and `electron.locator(css)`, which takes CSS only: no `text=`, `:has-text()`, `:visible`, or `>>`. Use `.filter({ hasText })` and `.filter({ has })` |
+| A query for an element behind an open modal | `electron.locator(css)`: the page behind a modal is `inert`, and `screen` queries leave an inert subtree out |
| `page.on('console')`, `electronApp.on('console')` | Recorded in the test's trace under App log, main-process lines prefixed `[main]`. A test cannot read them |
| `electronApp.close()` | Nothing: every test ends with the app quit |
diff --git a/docs/reference/errors.mdx b/docs/reference/errors.mdx
index b4b03202ef..5461f5872b 100644
--- a/docs/reference/errors.mdx
+++ b/docs/reference/errors.mdx
@@ -186,7 +186,7 @@ These appear in terminal output and in the report as plain string codes.
| `WORKER_PROTOCOL` | A worker reported the wrong unit, an attempt overlapped a live attempt, `openHost` tried to acquire an engine instance another host owns, or `host.openSession` tried to reuse a closed host or overlap an opening, live, or closing session. In `@e2e-dev/core`, `launch` on an engine instance another host owns, or `host.newSession` on a closed host or while a session is open | infrastructure | 3 |
| `SESSION_KEY_INVALID` | A worker received a session key that is not 32 bytes. Packaging or IPC fault. | infrastructure | 3 |
| `REPORT_WRITE_FAILED` | `report.json` or `ai-trace.json` could not be written. Recorded as a run error; the in-memory outcome is still complete. A `junit.xml`, `summary.md`, or `ctrf.json` that could not be written is a line on its reporter's stderr instead | infrastructure | 3 |
-| `EVALUATE_FAILED` | `browser.evaluate` threw inside the page, `electron.evaluate` threw in the main process (`@e2e-dev/electron`), a page timer threw while `browser.clock` ran it, or the page deleted or replaced a JavaScript built-in (such as `Map`) that the engine's in-page code needs, which fails later evaluates and locators (`@e2e-dev/web`) | test | 1 |
+| `EVALUATE_FAILED` | `browser.evaluate` threw inside the page, `electron.evaluate` threw in the main process or `window.evaluate` in a window's page (`@e2e-dev/electron`), a page timer threw while `browser.clock` ran it, or the page deleted or replaced a JavaScript built-in (such as `Map`) that the engine's in-page code needs, which fails later evaluates and locators (`@e2e-dev/web`) | test | 1 |
| `INTERRUPTED` | A user or CI signal aborted the run. A test cut short by `--max-failures` or the time limit also ends with this code, and its message names the limit; that run exits 1, not 130 | interrupted | 130 |
#### Test code errors
diff --git a/packages/electron/README.md b/packages/electron/README.md
index 03b08120c3..8cce1f16f3 100644
--- a/packages/electron/README.md
+++ b/packages/electron/README.md
@@ -57,8 +57,10 @@ test('signs in', async ({ app, screen }) => {
- **Act.** Trusted mouse and keyboard input, once the node is enabled, on
screen, and topmost at its point.
- **Windows.** The agent sees them as tabs. The `electron` fixture has
- `evaluate` (main process), `windows`, `waitForWindow`, `window`,
- `waitForDownload`, `onDialog`, and `locator` (CSS).
+ `launch` (per-test arguments and environment), `userDataDir`, `evaluate`
+ (main process), `windows`, `activeWindow`, `waitForWindow`, `window`,
+ `waitForDownload`, `onDialog`, `locator` (CSS), `keyboard`, and `mouse`. A
+ window has `evaluate` (its page) and `reload`.
- **Video.** The shown window's screencast, encoded to one `.webm` by ffmpeg,
which the engine downloads on the first recording when the machine has none.
- **Secrets.** Password fields report no value, and screenshots paint them
diff --git a/packages/electron/src/actions.ts b/packages/electron/src/actions.ts
index dfb19e5a3b..4bc16fefb6 100644
--- a/packages/electron/src/actions.ts
+++ b/packages/electron/src/actions.ts
@@ -146,7 +146,17 @@ export async function typeText(context: ActionContext, window: AppWindow, text:
await withModifiers(budget, window, ['ControlOrMeta'], () => keyboard.press('A'));
await budget.send(() => keyboard.press('Delete'));
}
- for (const character of text) await budget.send(() => keyboard.type(character));
+ await typeKeys(window, text, 0, budget);
+}
+
+/** Types text into whatever holds focus, key by key, `delayMs` apart: each character's key, or the character inserted when the layout has none. */
+export async function typeKeys(window: AppWindow, text: string, delayMs: number, budget: Budget): Promise {
+ let first = true;
+ for (const character of text) {
+ if (!first && delayMs > 0) await sleep(delayMs, budget.operation.signal);
+ first = false;
+ await budget.send(() => window.page.keyboard.type(character));
+ }
}
/** Presses a key in the shown window, wherever focus is. */
@@ -421,6 +431,8 @@ export async function withModifiers(budget: Budget, window: AppWindow, modifiers
const held: string[] = [];
try {
for (const modifier of modifiers) {
+ // One the test already holds (`electron.keyboard.down('Shift')`) stays the test's to release.
+ if (keyboard.holds(modifier)) continue;
await budget.send(() => {
held.push(modifier);
return keyboard.down(modifier);
diff --git a/packages/electron/src/app-process.ts b/packages/electron/src/app-process.ts
index b685733e03..584c59c12e 100644
--- a/packages/electron/src/app-process.ts
+++ b/packages/electron/src/app-process.ts
@@ -15,7 +15,8 @@ import type { ElectronMainModule } from './fixtures.ts';
import { closedWindow, invalidState, unsupported } from './errors.ts';
import { appDirectory } from './file-bound.ts';
import { ElectronProcess, type ProcessExit } from './launcher.ts';
-import { MainEvaluateError, MainProcess } from './main-process.ts';
+import { EvaluateError } from './evaluate.ts';
+import { MainProcess } from './main-process.ts';
import { REFUSED_ENV, type ResolvedElectronOptions } from './options.ts';
import { PageTarget } from './page.ts';
import type { Windows } from './windows.ts';
@@ -34,6 +35,16 @@ export interface LaunchSetup {
readonly env: Readonly>;
readonly userDataDir: string;
readonly attempt: EngineAttemptContext;
+ /** What `electron.launch()` added for this attempt, over the target's arguments and the engine's `env`. */
+ readonly extra?: LaunchExtra;
+}
+
+/** The arguments and variables one attempt's launches add to the target's own. */
+export interface LaunchExtra {
+ readonly args: readonly string[];
+ readonly env: Readonly>;
+ /** The directory the process starts in, over the engine's `cwd`. */
+ readonly cwd?: string;
}
/** How long the main process gets to answer a question whose answer is optional. */
@@ -209,8 +220,8 @@ export class AppProcess {
/** Starts the binary. Nothing is awaited: a binary that cannot start shows as a process that ended. */
private start(setup: LaunchSetup): RunningApp {
const { appPath, launchArguments } = setup.app;
- const args = [`--user-data-dir=${setup.userDataDir}`, ...(appPath === undefined ? [] : [path.resolve(setup.projectRoot, appPath)]), ...(launchArguments ?? [])];
- const process = new ElectronProcess({ executable: setup.executable, args, cwd: setup.projectRoot, env: launchEnv(setup.env, this.options.env) });
+ const args = [`--user-data-dir=${setup.userDataDir}`, ...(appPath === undefined ? [] : [path.resolve(setup.projectRoot, appPath)]), ...(launchArguments ?? []), ...(setup.extra?.args ?? [])];
+ const process = new ElectronProcess({ executable: setup.executable, args, cwd: path.resolve(setup.projectRoot, setup.extra?.cwd ?? this.options.cwd ?? '.'), env: launchEnv(setup.env, [this.options.env, setup.extra?.env ?? {}]) });
let withoutMain: () => void = () => undefined;
const none = new Promise((resolve) => {
withoutMain = () => resolve(undefined);
@@ -328,7 +339,7 @@ export class AppProcess {
});
session.on('Page.loadEventFired', () => {
this.windows.markLoaded(page);
- page.emit('load');
+ page.markLoaded();
});
session.on('Page.frameNavigated', ({ frame }) => {
if (frame.parentId !== undefined) return;
@@ -374,7 +385,7 @@ export class AppProcess {
const exiting = this.app === app && (closedWindow(cause) || /Execution context was destroyed/.test(String(cause)));
if (exiting) await answerWithin(app.process.exited, ANSWER_MS);
if (this.app !== app) throw new EngineError('INVALID_STATE', 'the app quit while electron.evaluate ran', { retryable: false, cause });
- if (!(cause instanceof MainEvaluateError)) throw cause;
+ if (!(cause instanceof EvaluateError)) throw cause;
// Its message is the test's, never read for a pattern.
throw new TestError('EVALUATE_FAILED', `electron.evaluate: ${cause.message}`, { cause });
}
@@ -572,20 +583,24 @@ async function placeDownloads(main: MainProcess, directory: string, withinMs: nu
/**
* The app's environment: the few variables of the run's that a process needs
- * to start and draw (`INHERITED_ENV`, and the locale's `LC_*`), with the
- * engine's `env` option over them. The rest of the run's environment stays
+ * to start and draw (`INHERITED_ENV`, and the locale's `LC_*`), with each of
+ * `layers` over them in turn: the engine's `env` option, then a test's own. The rest of the run's environment stays
* with the runner: it holds provider keys and tokens, and an app can log or
* upload what it is given. Never `ELECTRON_RUN_AS_NODE`, which would start
* the binary as plain Node.js, nor `NODE_OPTIONS`.
*/
-export function launchEnv(runEnv: Readonly>, extra: Readonly>): Record {
+export function launchEnv(runEnv: Readonly>, layers: readonly Readonly>[], platform: NodeJS.Platform = process.platform): Record {
const env: Record = {};
- // Windows reads a variable's name in any case.
+ // Windows reads a variable's name in any case: a later layer's `path` replaces an earlier `PATH`, never sits beside it.
+ const set = (key: string, value: string): void => {
+ if (platform === 'win32') for (const known of Object.keys(env)) if (known !== key && known.toUpperCase() === key.toUpperCase()) delete env[known];
+ env[key] = value;
+ };
for (const [key, value] of Object.entries(runEnv)) {
const name = key.toUpperCase();
- if (value !== undefined && (INHERITED_ENV.has(name) || name.startsWith('LC_'))) env[key] = value;
+ if (value !== undefined && (INHERITED_ENV.has(name) || name.startsWith('LC_'))) set(key, value);
}
- for (const [key, value] of Object.entries(extra)) if (!REFUSED_ENV.has(key.toUpperCase())) env[key] = value;
+ for (const layer of layers) for (const [key, value] of Object.entries(layer)) if (!REFUSED_ENV.has(key.toUpperCase())) set(key, value);
return env;
}
diff --git a/packages/electron/src/cdp/input.ts b/packages/electron/src/cdp/input.ts
index 6eacc0a619..2d96cd16f6 100644
--- a/packages/electron/src/cdp/input.ts
+++ b/packages/electron/src/cdp/input.ts
@@ -54,6 +54,12 @@ export class Keyboard {
return this.heldModifiers;
}
+ /** Whether a modifier is held now, by any name it is pressed by (`ControlOrMeta` too). */
+ holds(modifier: string): boolean {
+ const key = platformKey(modifier);
+ return isModifier(key) && this.heldModifiers.has(key);
+ }
+
/** Forgets what is held: the renderer that held it is gone. */
reset(): void {
this.heldModifiers.clear();
diff --git a/packages/electron/src/electron.ts b/packages/electron/src/electron.ts
index e9dd2d879a..a6afa8c975 100644
--- a/packages/electron/src/electron.ts
+++ b/packages/electron/src/electron.ts
@@ -4,8 +4,12 @@
* `electron.` step bounded by the action timeout.
*/
-import { ConfigurationError, isSecret, stepTimeout, type EngineFixtureContext, type FixtureOperation } from '@e2e-dev/core/engine';
+import { ConfigurationError, isSecret, stepTimeout, TestError, type EngineFixtureContext, type FixtureOperation } from '@e2e-dev/core/engine';
import type { Electron, ElectronMainModule, ElectronWindow } from './fixtures.ts';
+import { typeKeys } from './actions.ts';
+import { hasKey, type MouseButton } from './cdp/input.ts';
+import { unsupported } from './errors.ts';
+import { checkLaunchOptions } from './options.ts';
import type { ElectronSurface } from './surface.ts';
import type { AppWindow } from './windows.ts';
@@ -21,13 +25,80 @@ export function createElectronFixture(surface: ElectronSurface, context: EngineF
url: () => Promise.resolve(window.page.url()),
isActive: () => surface.isActiveWindow(window),
isClosed: () => window.page.isClosed(),
+ async evaluate(fn: (arg: A) => R | Promise, arg?: A): Promise {
+ if (holdsSecret(arg)) throw new ConfigurationError('POLICY_DENIED', 'window.evaluate cannot take a secret as its argument: fill it into a field with locator.fill');
+ return await surface.evaluateInWindow(window, fn, arg as A, context.operation());
+ },
+ reload: () => surface.reloadWindow(window, context.operation()),
activate: () => surface.activateWindow(window, context.operation()),
close: () => surface.closeWindow(window, context.operation()),
- }, { title: windowAction, url: windowAction, activate: windowAction, close: windowAction });
+ }, { title: windowAction, url: windowAction, activate: windowAction, close: windowAction, evaluate: windowAction, reload: windowAction });
handles.set(window, made);
return made;
};
+ const mouseButton = (options: { readonly button?: MouseButton } | undefined): MouseButton => {
+ const chosen = options?.button ?? 'left';
+ if (chosen !== 'left' && chosen !== 'right' && chosen !== 'middle') throw new TestError('INVALID_ARGUMENT', "electron.mouse takes { button: 'left' | 'right' | 'middle' }");
+ return chosen;
+ };
+ const numbers = (call: string, ...values: readonly unknown[]): void => {
+ if (values.some((value) => typeof value !== 'number' || !Number.isFinite(value))) throw new TestError('INVALID_ARGUMENT', `electron.mouse.${call} takes two numbers`);
+ };
+ const plainText = (value: unknown, method: string): string => {
+ if (isSecret(value)) throw new ConfigurationError('POLICY_DENIED', `electron.keyboard.${method} cannot take a secret: fill it into a field with locator.fill`);
+ if (typeof value !== 'string') throw new TestError('INVALID_ARGUMENT', `electron.keyboard.${method} takes a string`);
+ return value;
+ };
+ const holdKey = (direction: 'down' | 'up') => async (key: string): Promise => {
+ const name = plainText(key, direction);
+ if (!hasKey(name)) throw unsupported(`the keyboard has no key ${JSON.stringify(name)}: name a key such as "Shift" or "Enter", or a character of a US keyboard`);
+ await surface.input(`keyboard.${direction}`, (window, budget) => budget.send(() => window.page.keyboard[direction](name)), context.operation());
+ };
const electron: Electron = {
+ get userDataDir() {
+ return surface.dataDirectory();
+ },
+ async launch(options) {
+ // A secret would reach the app's command line or environment, where any process can read it.
+ if (holdsSecret(options)) throw new ConfigurationError('POLICY_DENIED', 'electron.launch() cannot take a secret in its arguments or variables');
+ const extra = checkLaunchOptions(options, surface.root);
+ await surface.launchWith(extra, context.operation(stepTimeout(options?.timeout, 'electron.launch') ?? context.timeouts.test));
+ },
+ activeWindow: () => handle(surface.shownWindow()),
+ keyboard: {
+ press: async (key) => surface.pressKey(plainText(key, 'press'), context.operation()),
+ down: holdKey('down'),
+ up: holdKey('up'),
+ async type(value, options) {
+ const delay = options?.delay ?? 0;
+ if (typeof delay !== 'number' || !Number.isFinite(delay) || delay < 0) throw new TestError('INVALID_ARGUMENT', 'electron.keyboard.type({ delay }) takes a number of milliseconds');
+ const typed = plainText(value, 'type');
+ // One budget for the whole text: the action timeout, and the time its delays ask on top.
+ await surface.input('keyboard.type', (window, budget) => typeKeys(window, typed, delay, budget), context.operation(context.timeouts.action + [...typed].length * delay));
+ },
+ async insertText(value) {
+ const inserted = plainText(value, 'insertText');
+ await surface.input('keyboard.insertText', (window, budget) => budget.send(() => window.page.keyboard.insertText(inserted)), context.operation());
+ },
+ },
+ mouse: {
+ async move(x, y) {
+ numbers('move(x, y)', x, y);
+ await surface.input('mouse.move', (window, budget) => budget.send(() => window.page.mouse.move(x, y)), context.operation());
+ },
+ async down(options) {
+ const pressed = mouseButton(options);
+ await surface.input('mouse.down', (window, budget) => budget.send(() => window.page.mouse.down(pressed)), context.operation());
+ },
+ async up(options) {
+ const released = mouseButton(options);
+ await surface.input('mouse.up', (window, budget) => budget.send(() => window.page.mouse.up(released)), context.operation());
+ },
+ async wheel(deltaX, deltaY) {
+ numbers('wheel(deltaX, deltaY)', deltaX, deltaY);
+ await surface.input('mouse.wheel', (window, budget) => budget.send(() => window.page.mouse.wheel(deltaX, deltaY)), context.operation());
+ },
+ },
async evaluate(fn: (electron: ElectronMainModule, arg: A) => R | Promise, arg?: A): Promise {
// A secret handle would reach the main process as its name and purpose, never its value: refused, as every JSON sink refuses one.
if (holdsSecret(arg)) throw new ConfigurationError('POLICY_DENIED', 'electron.evaluate cannot take a secret as its argument: resolve the value in the test and pass a string, or keep it out of the main process');
@@ -66,7 +137,17 @@ export function createElectronFixture(surface: ElectronSurface, context: EngineF
return context.locator({ kind: 'selector', selector });
},
};
+ const input: FixtureOperation = { kind: 'resource' };
return context.fixture('electron', electron, {
+ launch: { kind: 'resource', timeout: false },
+ keyboard: {
+ press: { ...input, label: (key) => String(key) },
+ down: { ...input, label: (key) => String(key) },
+ up: { ...input, label: (key) => String(key) },
+ type: { kind: 'resource', timeout: false, label: (value) => `${typeof value === 'string' ? [...value].length : 0} chars` },
+ insertText: { ...input, label: (value) => `${typeof value === 'string' ? [...value].length : 0} chars` },
+ },
+ mouse: { move: input, down: input, up: input, wheel: input },
evaluate: { kind: 'resource' },
waitForWindow: { kind: 'resource', timeout: false },
window: { kind: 'resource', timeout: (_which, options) => options?.timeout, label: (which) => JSON.stringify({ title: which.title?.toString(), url: which.url?.toString() }) },
diff --git a/packages/electron/src/engine-entry.ts b/packages/electron/src/engine-entry.ts
index 6447f7cb10..7a6e440ebf 100644
--- a/packages/electron/src/engine-entry.ts
+++ b/packages/electron/src/engine-entry.ts
@@ -11,4 +11,4 @@ export type { ElectronEngine } from './engine.ts';
export { electron as default } from './engine.ts';
export type { ElectronOptions } from './options.ts';
export type { Dialog, DialogHandler } from './dialogs.ts';
-export type { Electron, ElectronFixtures, ElectronMainModule, ElectronWindow, WindowMatcher } from './fixtures.ts';
+export type { Electron, ElectronFixtures, ElectronKeyboard, ElectronLaunchOptions, ElectronMainModule, ElectronMouse, ElectronWindow, WindowMatcher } from './fixtures.ts';
diff --git a/packages/electron/src/evaluate.ts b/packages/electron/src/evaluate.ts
new file mode 100644
index 0000000000..617280cbc1
--- /dev/null
+++ b/packages/electron/src/evaluate.ts
@@ -0,0 +1,111 @@
+/**
+ * Test code run inside the app, in its main process or in a window's page:
+ * the function sent as source text, its argument as a protocol value, and
+ * what it returns brought back as plain data.
+ */
+
+import type { Protocol } from 'devtools-protocol';
+import { TestError } from '@e2e-dev/core/engine';
+import type { Session } from './cdp/connection.ts';
+
+/** What a function run in the app threw: its own failure, not the engine's. */
+export class EvaluateError extends Error {}
+
+/** Refuses an argument that is not JSON, in the caller's name: it crosses the protocol as a value. */
+export function checkJsonArgument(arg: unknown, caller: string): void {
+ try {
+ JSON.stringify(arg);
+ } catch (cause) {
+ throw new TestError('INVALID_ARGUMENT', `${caller}: its argument is not JSON (${cause instanceof Error ? (cause.message.split('\n')[0] ?? '') : String(cause)}); pass plain data`, { cause });
+ }
+}
+
+/**
+ * Calls the function `source` on the remote object `objectId` with `leading`
+ * and then `arg`, awaits it, and returns its result as plain data
+ * (`plainData`). Rejects with `EvaluateError` when the function throws.
+ */
+export async function callForPlainData(
+ session: Session,
+ call: { readonly objectId: string; readonly source: string; readonly leading?: readonly Protocol.Runtime.CallArgument[]; readonly arg: unknown; readonly userGesture?: boolean },
+): Promise {
+ const { result, exceptionDetails } = await session.send('Runtime.callFunctionOn', {
+ objectId: call.objectId,
+ functionDeclaration: `async function (...args) { return (${plainData.toString()})(await (${call.source})(...args)); }`,
+ arguments: [...(call.leading ?? []), call.arg === undefined ? {} : { value: call.arg }],
+ returnByValue: true,
+ awaitPromise: true,
+ ...(call.userGesture === true ? { userGesture: true } : {}),
+ });
+ if (exceptionDetails !== undefined) throw new EvaluateError(describeException(exceptionDetails));
+ // NaN, an infinity, and -0 have no JSON: the protocol names them instead.
+ return result.unserializableValue === undefined ? result.value : Number(result.unserializableValue);
+}
+
+/**
+ * A function's source as an expression. A method written in shorthand
+ * (`{ run() {} }.run`) prints without the `function` keyword, which is put
+ * back. The source is only compiled here, never run.
+ */
+export function functionSource(fn: (...args: never[]) => unknown, caller: string): string {
+ if (typeof fn !== 'function') throw new TestError('INVALID_ARGUMENT', `${caller} takes a function`);
+ const source = fn.toString();
+ if (compiles(source)) return source;
+ const method = source.replace(/^(async\s+)?(\*\s*)?/, (_match, async: string | undefined, star: string | undefined) => `${async ?? ''}function ${star ?? ''}`);
+ if (compiles(method)) return method;
+ throw new TestError('INVALID_ARGUMENT', `${caller}: its function cannot be sent as source text; pass an arrow function or a function expression`);
+}
+
+function compiles(source: string): boolean {
+ try {
+ // oxlint-disable-next-line no-new-func -- compiled to check its syntax, never called
+ void new Function(`(${source})`);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/** What a thrown value says of itself, on one line. */
+export function describeException(details: Protocol.Runtime.ExceptionDetails): string {
+ const { exception } = details;
+ if (exception?.description !== undefined) return exception.description.split('\n')[0] ?? details.text;
+ return exception?.value === undefined ? details.text : `${details.text} ${String(exception.value)}`;
+}
+
+/**
+ * A value as the plain data that crosses the protocol: objects and arrays of
+ * primitives. A function or a symbol is left out, as is a reference back to
+ * an object that holds it, so a `BrowserWindow` or a timer comes back as the
+ * plain part of what it is rather than failing the call. Runs in the main
+ * process, sent as source text: self-contained.
+ */
+export function plainData(value: unknown): unknown {
+ const holders = new Set