Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .changeset/electron-per-test-launch.md
Original file line number Diff line number Diff line change
@@ -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 `<button><i class="fa fa-search"></i> Scan</button>`, 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`.
8 changes: 8 additions & 0 deletions apps/electron-testbed/app/controls.html
Original file line number Diff line number Diff line change
Expand Up @@ -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'; }
</style>
</head>
<body>
Expand Down Expand Up @@ -95,6 +96,13 @@ <h2 aria-level="4">Levels</h2>
<output data-testid="more-clicks">0</output>
<div data-testid="disabled-host" aria-disabled="true"></div>
<output data-testid="host-clicks">0</output>
<button data-testid="glyph-button"><i class="glyph"></i> Scan</button>
<div role="toolbar" aria-label="Selection" style="width: 100%"><span><span id="unselect"><i></i> <span>Unselect All</span></span></span></div>
<output data-testid="unselect-clicks">0</output>
<button disabled style="width: 100%; text-align: left"><span>Wide save</span></button>
<table style="width: 100%"><tr><td><span id="open-row">Open row</span></td></tr></table>
<output data-testid="open-row-clicks">0</output>
<div role="option" tabindex="0" data-testid="composite-row" aria-label="Composite row"><input aria-label="Row name" data-testid="row-name" /></div>
</section>
<p data-testid="far-below" style="margin-top: 3000px">Far below</p>
<script src="controls.js"></script>
Expand Down
4 changes: 4 additions & 0 deletions apps/electron-testbed/app/controls.js
Original file line number Diff line number Diff line change
Expand Up @@ -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());
22 changes: 22 additions & 0 deletions apps/electron-testbed/tests/controls.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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' });
Expand Down
140 changes: 140 additions & 0 deletions apps/electron-testbed/tests/fixture.e2e.ts
Original file line number Diff line number Diff line change
@@ -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<unknown>): Promise<unknown> {
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<number> => 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' });
});
});
70 changes: 67 additions & 3 deletions docs/electron.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 |
Expand Down Expand Up @@ -300,14 +364,14 @@ 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

| 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<string, string>` | `{}` | 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) |
Expand Down
Loading
Loading