diff --git a/.dev/skills/authoring-docs/SKILL.md b/.dev/skills/authoring-docs/SKILL.md index f67e34dd8c..a28ac03bd1 100644 --- a/.dev/skills/authoring-docs/SKILL.md +++ b/.dev/skills/authoring-docs/SKILL.md @@ -11,7 +11,7 @@ Readers skim. They read the headings, the first sentence of each section, the code blocks, and the tables, then leave. Write for that reader. Show the fast path first and fold everything else. -Model pages: `docs/bug-bash.mdx` and `docs/quickstart.mdx`. When in doubt, +Model pages: `docs/explore.mdx` and `docs/quickstart.mdx`. When in doubt, copy their shape. ## IMPORTANT: shorten every page @@ -57,13 +57,13 @@ of three kinds, and work them in this order. Keep a guarantee the reader would otherwise doubt, even when it reads like "works as it does locally". Check whether another page says it can - fail. `browser.mdx` says a provider without `downloads` fails, so a + fail. `reference/web.mdx` says a provider without `downloads` fails, so a provider page keeps the line that downloads work. 2. **Merge what's said twice.** Each fact has one place. - A lede paragraph that previews a section becomes a link to it. - A "Before you start" whose items fit in two short sentences becomes a `Note` in the first task. Keep the section when its items need - bullets, as in `docs/bug-bash.mdx`. + bullets, as in `docs/explore.mdx`. - A section that explains one option moves under the config that sets it. - A list and a table that describe the same fields become one table, @@ -181,7 +181,8 @@ description: ## Vendor logos -The sidebar shows no icons. Don't set `icon:` in a page's frontmatter; +The sidebar shows an icon on each group (`icon` on the group in +`docs/docs.json`), never on a page. Don't set `icon:` in a page's frontmatter; `pnpm docs:check` fails on one. **A vendor page gets the vendor's logo on its cards.** A vendor page is @@ -457,8 +458,9 @@ Each group opens with one table, one row per entry. Keep it to the minimum: - A short example. Show a default as a code comment: `// default: 5000`. - Accepted values as a list or a table. Errors as a `| Throws | When |` table. - At most one ``. `` only for data loss or a leaked secret. -- TypeScript declarations keep their JSDoc, in the entry or under - `## Types`. They are the contract. +- TypeScript declarations show signatures and types only, with no JSDoc, + in the entry or under `## Types`. A default, limit, unit, or error goes in + the entry's prose or tables, stated once. - No Version History section; nothing reliable feeds it. ### Keep every fact diff --git a/README.md b/README.md index ac4d781229..79df338c10 100644 --- a/README.md +++ b/README.md @@ -81,7 +81,7 @@ runs your suite. The server needs no model. } ``` -See the [MCP server docs](https://e2e.com/docs/mcp-server) for setup and +See the [MCP server docs](https://e2e.com/docs/coding-agents#let-the-agent-use-the-app) for setup and every tool. ## Packages diff --git a/docs/agent-steps.mdx b/docs/agent-steps.mdx index 615b78e50f..6ceff742f2 100644 --- a/docs/agent-steps.mdx +++ b/docs/agent-steps.mdx @@ -1,6 +1,6 @@ --- title: How agent steps work -description: What the model sees, what it may do, how a step ends, and what it costs. +description: "Learn how an agent step runs in e2e, from what the AI model sees and which actions it may take to how a step ends and what it costs in model calls." "og:image": "https://e2e.com/docs/images/og/agent-steps.png?v=321767dc3b" "twitter:image": "https://e2e.com/docs/images/og/agent-steps.png?v=321767dc3b" --- @@ -126,6 +126,45 @@ Use `expect` for exact checks, and give each `act` the steps toward one [goal](/core-concepts#goals). When the provider caches prompts, `--debug` shows the cached share of input tokens per step. +## Split a long flow into goals + +Start with one `agent.act` call for the behavior under test. Split it at a +meaningful transition when the next step needs a known state (such as the +payment page of a long checkout), when a long flow risks the `maxSteps` or +`maxModelCalls` budgets, or when a failure in the middle needs its own step +boundary. Say why the split is needed, and wait for the intermediate screen +state before you continue. Each call has its own +[budgets](/reference/agent#budgets) and can replay from its own recording. + +```ts title="Complete one checkout across two screens" +import { expect, test } from 'e2e'; + +test('places an order with a saved card', async ({ app, agent, screen }) => { + await app.open('/checkout'); + + // The saved card can load after the Payment heading appears. + await agent.act('Fill the Shipping address with {address}, then choose Continue to payment.', { + params: { address: '12 Market Street' }, + }); + await screen.getByRole('radio', 'Test card').waitFor(); + await agent.act('Select the saved Test card and choose Place order.'); + + await expect(screen.getByText('Order confirmed')).toBeVisible(); +}); +``` + +- **Wait after setup, assert at the end.** When setup uses `agent.act`, end + setup with a wait for the starting state, and check the final outcome in + the assert block. A later passing verification check, such as a locator + assertion or `locator.waitFor()`, confirms earlier goals for the + [replay cache](/cache#when-a-recording-is-written). An `expect` on a plain + value and `expect.poll` do not. +- **Match the UI's wording.** Use the field and button names shown on + screen, and say the order when it matters, such as filling shipping info, + picking a delivery option, then placing the order. +- **When a goal fails, tighten the instruction.** Terms that every goal + shares go into the agent's [`context`](/agents) instead. + ## Next diff --git a/docs/agentic-vs-deterministic.mdx b/docs/agentic-vs-deterministic.mdx deleted file mode 100644 index 8084d7e8bf..0000000000 --- a/docs/agentic-vs-deterministic.mdx +++ /dev/null @@ -1,125 +0,0 @@ ---- -title: Agentic or deterministic -description: Choose agentic or deterministic actions and assertions for your end-to-end tests. ---- - -Agentic testing lets you describe what a user wants to do and what the screen -should show in natural language. The agent picks the actions and checks the -outcome, so you don't spend time maintaining selectors when the UI changes. - -Deterministic testing spells out every interaction and assertion in code. -Both test user outcomes, and e2e lets you mix them freely in the same test. - -## When to use agentic tests? - -Use agentic tests when UI changes keep forcing you to update selectors -in your tests. They also suit flows that take many interactions but are -easy to describe in plain English, such as filling out and submitting a form. - -`agent.act` lets you describe a user intention, such as applying a -discount code. The agent figures out which controls to use and what to do. -`agent.assert` checks whether the screen shows the result you describe, -such as a discount applied to the total. - -For example, inside a test with the `app` and `agent` fixtures: - -```ts -await app.open('/checkout'); -await agent.act('apply the discount code SUMMER'); -await agent.assert('the checkout shows code SUMMER applied with a 10% discount'); -``` - -You don't need to name the discount field, the button that applies it, -or the element that shows the result. - -Tests tied to CSS classes or test IDs need edits when those identifiers -change. Move a button or redesign a form, and the agent can still carry -out the user's intention using what's on screen. - -Agentic tests enable monitoring with real data on staging or production -without seeding deterministic data, because agents adapt to your app. -Use a test account there: the model sees what's on screen. See -[Security](/security). - -For a complex flow, describe the steps toward one outcome in plain -English. See [Goals](/core-concepts#goals) for when to split the flow -into calls and wait for an intermediate state. - -## When to use agentic assertions? - -Agentic assertions are useful when several wordings or layouts would -satisfy the same requirement. For example, a validation message can -explain what's wrong without matching one exact sentence: - -```ts -await agent.assert('the error message explains that an email address is required'); -``` - -For a visual check, add `vision: true` so the model also sees a screenshot: - -```ts -await agent.assert('the chart trends upward', { vision: true }); -``` - -`agent.assert` checks the current screen and fails if the statement is -false or the evidence is insufficient. Use `agent.waitFor` when the UI -still needs time to reach the expected state. See -[Assertions](/core-concepts#assertions) for both methods. - -## When to use deterministic tests? - -Use locators for low-level mechanics that are themselves under test (such as -an empty submission, a keyboard shortcut, or a drag offset), sign-in setup -tests, or projects that run without a model. You specify each field and button -in code, as in this discount test: - -```ts -await app.open('/checkout'); -await screen.getByLabel('Discount code').fill('SUMMER'); -await screen.getByRole('button', 'Apply').tap(); -await expect(screen.getByRole('status')).toHaveText('10% off'); -``` - -These actions and checks make no model calls. Prefer roles and labels so -the test refers to controls the user recognizes. Deterministic tests don't -have to depend on CSS classes or test IDs. - -Use deterministic assertions when you can express the expected result -as an exact value, count, or state. They check it without model judgment. -If a validation message must use specific wording, check that text with -`expect`. - -## Combine agentic with deterministic tests - -Choose actions and assertions independently. You can let the agent find -its way through a changing UI, then check an exact value with `expect`: - -```ts -await agent.act('apply the discount code SUMMER'); -await expect(screen.getByRole('status')).toHaveText('10% off'); -``` - -You can also use locators to fill and submit a form, then use -`agent.assert` to check whether its validation message explains the problem. - -Adaptation follows the goal you write. A vague instruction can allow a -result you didn't intend. If a specific path matters, name it in the goal -or use locators for those actions. An `expect` after `agent.act` catches -a goal that passed the wrong way. - -Model calls add latency, cost, and occasional mistakes. The -[replay cache](/cache) solves most of that by replaying recorded `agent.act` -actions with zero model calls, while assertions always run live. When the UI -changes and a recording no longer matches, the agent steps in to adapt unless -you enable strict cache mode. See [Self-healing tests](/self-healing). - -## Next - - - - Write goals, assertions, and locator steps. - - - See how an agent recovers when a recorded flow changes. - - diff --git a/docs/agents.mdx b/docs/agents.mdx index 6b7f1b113d..8bb3a63f0d 100644 --- a/docs/agents.mdx +++ b/docs/agents.mdx @@ -1,6 +1,6 @@ --- title: Agents and personas -description: Configure several agents in one suite, pin tests to them, and run one flow as each persona. +description: "Configure several named AI agents in one suite, each with its own model, instructions, and tools, pin tests to them, and run one flow as different personas." "og:image": "https://e2e.com/docs/images/og/agents.png?v=94dc88725f" "twitter:image": "https://e2e.com/docs/images/og/agents.png?v=94dc88725f" --- diff --git a/docs/api-testing.mdx b/docs/api-testing.mdx index 4e7ecde5d5..3ba0d59685 100644 --- a/docs/api-testing.mdx +++ b/docs/api-testing.mdx @@ -1,8 +1,9 @@ --- title: API -description: Check your API with the request fixture and value matchers, in the same files and run as UI tests. +description: "Test HTTP APIs with the request fixture and value matchers, in the same files, run, and report as your UI tests, with no model calls." "og:image": "https://e2e.com/docs/images/og/api-testing.png?v=bd427bf4fd" "twitter:image": "https://e2e.com/docs/images/og/api-testing.png?v=bd427bf4fd" +keywords: [HTTP, REST, request] --- API tests use the [`request`](/reference/request) fixture and value matchers diff --git a/docs/authentication.mdx b/docs/authentication.mdx index f456862ee8..c612b21a1d 100644 --- a/docs/authentication.mdx +++ b/docs/authentication.mdx @@ -1,8 +1,9 @@ --- title: Authentication -description: Sign in once, reuse the session across tests, and pass secrets without exposing them to the model. +description: "Sign in once in a setup test, reuse the saved session across tests, and pass passwords and other secrets without exposing them to the AI model." "og:image": "https://e2e.com/docs/images/og/authentication.png?v=6e061842b8" "twitter:image": "https://e2e.com/docs/images/og/authentication.png?v=6e061842b8" +keywords: [login, sign in, password, secrets, session] --- import { Video } from './snippets/video.jsx'; diff --git a/docs/browser.mdx b/docs/browser.mdx deleted file mode 100644 index 4b00505844..0000000000 --- a/docs/browser.mdx +++ /dev/null @@ -1,591 +0,0 @@ ---- -title: Working with the browser -description: Mock an API, handle a dialog, download a file, reach into an iframe, and pick a browser. -"og:image": "https://e2e.com/docs/images/og/browser.png?v=9e41078fc1" -"twitter:image": "https://e2e.com/docs/images/og/browser.png?v=9e41078fc1" ---- - -The `browser` fixture of `@e2e-dev/web` mocks requests, handles dialogs, -downloads files, and runs code in the page. The engine runs Chromium, -Firefox, and WebKit through -[Playwright](https://github.com/microsoft/playwright). For navigation, -interactions, and checks, use `screen`, `app`, and `expect`. - -Import `test` from `@e2e-dev/web` to get `browser`: - -```ts -import { test } from '@e2e-dev/web'; -import { expect } from 'e2e'; - -test('the dashboard loads', async ({ app, screen, browser }) => { - await app.open('/dashboard'); - await expect(browser).toHaveURL('/dashboard'); - await expect(browser).toHaveTitle(/Dashboard/); - await expect(screen.getByRole('heading', 'Overview')).toBeVisible(); -}); -``` - -In a suite with device targets, add `{ platforms: ['web'] }` to a test -that uses `browser`, so the runner skips it on devices. - -## Mock an API - -`browser.route` intercepts requests for the rest of the attempt, also after -`app.restart()` and a session restore. Register it before the page opens. - -```ts -await browser.route('**/api/quote', async (route) => { - await route.fulfill({ json: { cents: 4200 } }); -}); - -await app.open('/checkout'); -await expect(screen.getByText('$42.00')).toBeVisible(); -``` - -- Each handler calls exactly one of `fulfill`, `continue`, `fallback`, or - `abort`. -- The newest route runs first. `continue` sends the request to the network. - `fallback` passes it to the route registered before. -- An `expect` that fails in a handler fails the test, at the next step or - at the end of the test. - -Start `browser.waitForResponse` before the action that triggers the request, -usually in `Promise.all`. It also works before the first `browser.goto` or -`app.open`: - -```ts -const [response] = await Promise.all([ - browser.waitForResponse('**/api/orders'), - screen.getByRole('button', 'Place order').tap(), -]); -expect(response.status).toBe(201); -``` - -Use `browser.waitForRequest` to resolve when the page sends the request, before -any response arrives. Both methods accept a URL glob, a `RegExp`, -`{ method, url }`, or a predicate function such as -`(response) => response.request.method === 'POST' && response.status === 201`. -See [`waitForResponse`](/reference/web#waitforresponse) and -[`waitForRequest`](/reference/web#waitforrequest). - -## Handle a dialog - -An unhandled `alert`, `confirm`, or `prompt` fails the next step. Register a -handler first: - -```ts -const off = await browser.onDialog('accept'); -await screen.getByRole('button', 'Delete').tap(); -await off(); -``` - -A function handler gets the dialog and must call `accept(text?)` or -`dismiss()`. - -## Download a file - -```ts -import { readFile } from 'node:fs/promises'; - -const file = await browser.waitForDownload(() => - screen.getByRole('link', 'Export CSV').tap(), -); -const csv = await readFile(file.absolutePath, 'utf8'); -expect(csv).toContain('Invoice'); -``` - -e2e saves the file as a `download` artifact. Read it through -`file.absolutePath`, which works with hosted browsers too. `file.path` is -relative to the attempt's artifact directory, not to the project. - -## Reach into an iframe - -`browser.frameLocator` scopes queries to a frame: - -```ts -const payment = browser.frameLocator('#payment-frame'); -await payment.getByLabel('Card number').fill('4242424242424242'); -``` - -In a frame, `locator` takes a CSS or XPath selector, and `frameLocator` -enters a nested frame: - -```ts -const editor = browser.frameLocator('#result'); -await editor.locator('#upload').setInputFiles('fixtures/photo.png'); -await expect(editor.frameLocator('#preview').getByRole('heading', 'Uploaded')).toBeVisible(); -``` - -`browser.locator('css or xpath')` does the same on the page. Use a selector -only when role, label, and test-id queries can't find the element. For a -match made ambiguous by a hidden duplicate, try `{ visible: true }` first. - -The agent's semantic tree shows a frame from another site, such as a hosted -card field, as an `iframe` element with none of its content -([site check](/reference/security#site-check)). The agent reaches that -content only through screenshots. Use `frameLocator` for steps in that -frame. To judge its content with `agent.assert`, pass -[`vision`](/reference/agent#vision). An `agent.act` whose only change is in -that frame never records a [replay](/cache#when-a-recording-is-written). - -## Read from the page - -`browser.evaluate` runs a function in the page. e2e serializes the -function, so it can't use test variables. Pass data as the second argument: - -```ts -const count = await browser.evaluate(() => document.querySelectorAll('li').length); -const flag = await browser.evaluate((name: string) => window.localStorage.getItem(name), 'featureFlags'); -``` - -Use `evaluate` only for state that `screen` can't read. - -## Run a script before the page - -An init script runs in every document before the page's own scripts. Use it -to mock a browser API, seed `Math.random`, or set a flag the app reads at -boot. For every test: - -```ts -web({ initScripts: [{ path: 'tests/init.js' }] }) -``` - -For one test, before the page opens: - -```ts -await browser.addInitScript((value) => { Math.random = () => value; }, 0.5); -await app.open('/raffle'); -``` - -See [init scripts](/reference/web#init-scripts). - -## Emulate dark mode and reduced motion - -`colorScheme` and `reducedMotion` set what the page's `@media` rules and -`matchMedia` read, from the first paint. For every test: - -```ts -web({ colorScheme: 'dark', reducedMotion: 'reduce' }) -``` - -For one test, call `browser.emulateMedia`. Call it before the page opens to -load the page with those values: - -```ts -await browser.emulateMedia({ reducedMotion: 'reduce' }); -await app.open('/'); -``` - -A value holds for the rest of the test, through `app.restart()` and -`app.clearState()`. See [media emulation](/reference/web#media-emulation). - -## Go offline - -`browser.setNetwork('offline')` cuts the network for every tab and service -worker, until the test ends or goes back online: - -```ts -await app.open('/'); -await browser.setNetwork('offline'); -await screen.getByRole('button', 'Refresh').tap(); -await expect(screen.getByText('You are offline')).toBeVisible(); -``` - -`browser.reload()` loads a cached service-worker page when offline; navigating -to an uncached URL fails. See [`setNetwork`](/reference/web#setnetwork). - -## Control time - -`browser.clock` sets the time the page reads and runs its timers on your -command, as Playwright's `page.clock` does. Install it before the page -opens, then pause it: - -```ts -await browser.clock.install({ time: new Date('2024-02-02T08:00:00Z') }); -await browser.clock.pauseAt(new Date('2024-02-02T09:00:00Z')); -await app.open('/offer'); -await browser.clock.runFor('00:10'); // fires every timer due in 10 seconds -await expect(screen.getByText('Offer expired')).toBeVisible(); -``` - -The clock covers every tab and holds for the rest of the test. Your test's -own timeouts and waits keep real time. See [clock](/reference/web#clock). - -## Cookies - -```ts -await browser.setCookies([{ url: 'http://localhost:3000', name: 'tz', value: 'UTC' }]); -``` - -Cookie URLs must be valid `http:` or `https:` URLs (invalid entries are -rejected as a batch so no partial cookies get set). - -## Pick a browser - -The browser is an option of the engine, `chromium` by default. Two -browsers on one app are two targets, as in -[One size per target](/web#one-size-per-target): - -```ts title="Target fragment" -{ name: 'webkit', engine: web({ browser: 'webkit' }), app }, -``` - -In CI, install the extra browser with the -[install command](/reference/web#installing-browsers): - - -```bash npm -npx @e2e-dev/web install webkit --with-deps -``` - -```bash pnpm -pnpm exec e2e-web install webkit --with-deps -``` - -```bash bun -bunx @e2e-dev/web install webkit --with-deps -``` - - -`browser.name` is the browser the test runs in, and `browser.version` the -version it reports. Skip a test on one browser from its body: - -```ts -test('copies the invite link', async ({ app, screen, browser }) => { - test.skip(browser.name === 'webkit', 'not supported on WebKit yet'); - await app.open('/invite'); -}); -``` - -See [`name`, `version`](/reference/web#name-version). - -`connect` attaches to a remote Chromium over CDP instead of launching one, -or to another browser that speaks CDP, such as a running -[Lightpanda](/integrations/lightpanda) or [Moli](/integrations/moli). -To set sizes, see [Viewports](/web#viewports). - -## Hosted browsers - -A browser provider leases a browser from a service and gives the engine its -CDP endpoint. Pass it as `browser`. The engine gives each browser back when -its scope ends, on every exit path, so a session billed by the minute stops -when the run no longer uses it. - -| Service | Provider | -| --- | --- | -| [Kernel](/integrations/kernel) | `kernel()` from `@e2e-dev/kernel` | -| [Notte](/integrations/notte) | `notte()` from `@e2e-dev/notte` | -| [smol machines](/integrations/smol) microVMs on your own computer | `smol()` from `@e2e-dev/smol` | -| [Lightpanda](/integrations/lightpanda), the open-source headless browser, on your own machine | `lightpanda()` from `@e2e-dev/lightpanda` | -| [Moli](/integrations/moli), a local browser with on-demand layout and screenshots | `moli()` from `@e2e-dev/moli` | -| [TestMu AI](/integrations/testmu#run-web-targets-in-browsers) | `testmuBrowsers()` from `@e2e-dev/testmu/web` | -| [E2B](/integrations/e2b#run-web-targets-in-browsers) sandboxes | `e2bBrowsers()` from `@e2e-dev/e2b/web` | -| [Revyl](/integrations/revyl#run-web-targets-in-browsers) | `revylBrowsers()` from `@e2e-dev/revyl/web` | -| Any other service | Your own provider, a few dozen lines in your project | - -When the service shows the window in a live view, add `viewport: null` so -the page [fills the window](/web#fill-the-window). - -A provider implies a browser the engine drives as Chromium over CDP, -Chromium itself, Lightpanda, or Moli, and can't be combined with `connect`. A -target with nothing to run leases nothing. - -### Write a provider - -A provider implements this interface: - -```ts -export interface BrowserProvider { - /** Label in progress lines and error messages. */ - readonly name: string; - /** `worker` (default): one browser per worker slot for the run. `attempt`: a fresh browser per attempt. */ - readonly scope?: 'worker' | 'attempt'; - acquire(request: BrowserRequest): Promise; - release(lease: BrowserLease, context: BrowserReleaseContext): Promise; - /** Optional: resolves CDP handshake headers from the worker's environment. */ - cdpHeaders?(lease: BrowserLease, context: BrowserRequest): Readonly> | Promise>>; - /** Optional: the service's own recording of the browser, in the worker, for an attempt that records video. */ - record?(lease: BrowserLease, context: ProviderRecordContext): Promise; - /** Optional: serves `browser.waitForDownload` for a browser on another machine. */ - readonly downloads?: BrowserProviderDownloads; - /** Optional: releases the run's leases a dead worker left open, once the run ends; resolves to their ids. */ - sweep?(context: BrowserReleaseContext): Promise; -} - -export interface BrowserProviderDownloads { - /** Absolute directory on the browser's machine the browser saves downloads to. */ - readonly dir: string; - /** The bytes of one finished download, `file` a path under `dir`, read off the leased browser. */ - read(lease: BrowserLease, file: string, context: BrowserDownloadContext): Promise; -} - -export interface BrowserLease { - /** The provider's handle (a session id), handed back to `release`. */ - readonly id: string; - /** `ws://`, `wss://`, or `http://` DevTools endpoint to attach to over CDP. */ - readonly cdpEndpoint: string; - /** Endpoint to reattach to the same browser after a transport drop; per-attempt leases only. */ - readonly reconnectEndpoint?: string; -} -``` - -`acquire` gets the run id, the target, the worker slot and slot count, the -attempt id for a per-attempt lease, the run's environment, an abort signal, -and a `log` that reaches the reporter. Read tokens from `request.env`, not -`process.env`. - -A lease is JSON data. `release` gets back the object `acquire` returned, so -a provider can keep its own fields on it. Only `id`, `cdpEndpoint`, and -`reconnectEndpoint` travel to the worker, so key anything a worker uses, -such as a recording, on `lease.id`. - -For an authenticated CDP connection, implement `cdpHeaders(lease, request)` -and read credentials from `request.env` in the worker. Headers never travel -in lease JSON and do not become page request headers. - -Against a typical session API, a provider sends three requests: create a -session, poll it until it has a DevTools endpoint, and stop it. - - - -```ts title="browser-provider.ts" -import type { BrowserProvider } from '@e2e-dev/web'; - -/** - * Leases browsers from a service that starts a Chromium per session and - * exposes its DevTools endpoint. Replace the three requests with your - * service's API. - */ -export function hostedBrowsers(options: { serviceUrl: string; scope?: 'worker' | 'attempt' }): BrowserProvider { - return { - name: 'hosted-browsers', - scope: options.scope ?? 'worker', - async acquire(request) { - const token = request.env['BROWSER_SERVICE_TOKEN']; - if (token === undefined || token === '') throw new Error('BROWSER_SERVICE_TOKEN is not set'); - const headers = { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }; - // 1. Ask for a browser; name the session after the run so it can be found later. - const created = await fetch(`${options.serviceUrl}/sessions`, { - method: 'POST', - headers, - body: JSON.stringify({ - name: `e2e ${request.runId} ${request.targetName} ${request.attemptId ?? `slot ${request.slot + 1} of ${request.slots}`}`, - }), - signal: request.signal, - }); - if (!created.ok) throw new Error(`browser service: HTTP ${created.status}`); - const { id } = (await created.json()) as { id: string }; - // 2. Wait until the session exposes its DevTools endpoint. - for (;;) { - const response = await fetch(`${options.serviceUrl}/sessions/${id}`, { headers, signal: request.signal }); - const session = (await response.json()) as { status: string; cdpUrl?: string; viewerUrl?: string }; - if (session.status === 'ready' && session.cdpUrl !== undefined) { - if (session.viewerUrl !== undefined) request.log(`watch at ${session.viewerUrl}`); - return { id, cdpEndpoint: session.cdpUrl }; - } - if (session.status !== 'starting') throw new Error(`browser service: session ${id} is ${session.status}`); - await new Promise((resolve) => setTimeout(resolve, 2_000)); - } - }, - async release(lease, context) { - // 3. Stop the session; the run waits for this within cleanupTimeout. - const token = context.env['BROWSER_SERVICE_TOKEN'] ?? ''; - await fetch(`${options.serviceUrl}/sessions/${lease.id}/stop`, { - method: 'POST', - headers: { Authorization: `Bearer ${token}` }, - signal: context.signal, - }); - }, - }; -} -``` - -```ts title="e2e.config.ts" -import type { E2EConfig } from 'e2e'; -import { web } from '@e2e-dev/web'; -import { hostedBrowsers } from './browser-provider.ts'; - -export default { - targets: [ - { - name: 'hosted', - engine: web({ - browser: hostedBrowsers({ serviceUrl: 'https://browsers.example.com' }), - }), - app: { url: 'https://staging.example.com' }, - }, - ], - workers: 2, -} satisfies E2EConfig; -``` - -Two workers lease two sessions in parallel and keep them for the run. - - - -### Pick a lease scope - -`scope: 'worker'`, the default, keeps one browser per worker slot for the -whole run. `scope: 'attempt'` gives each attempt, retries included, a fresh -browser that no earlier test touched, for the cost of a session start per -attempt. A hosted session costs money while it runs, so keep `workers` at -what the suite can fill. - -A worker that crashes or gets killed can't release its leases. Implement -`sweep` to clean up any orphaned leases at the end of a run (once per -target, using provider tags or a local lease journal). A failed sweep logs a -line without failing the run. Without `sweep`, orphaned browsers stay open -until the service ends them. - - -- All worker slots lease their browsers in parallel at startup; if any slot - fails, the run aborts before tests begin and releases the rest. -- Leases are released after the last worker exits (within `cleanupTimeout`), - even on failures or Ctrl-C. -- If a worker's browser drops mid-run, the worker leases a replacement on - the next attempt and releases it on exit. Because `acquire` can run inside - a worker process, don't rely on in-memory state from the main process. -- Whichever side acquired a lease releases it once. - - - -Attempt-scoped tests run in the browser's persistent default context on its -first tab, so the same limits as -[`connect.reconnectEndpoint`](/reference/web#recovering-a-cdp-transport) -apply: - -- `headers`, `basicAuth`, `userAgent`, `locale`, `timezoneId`, and - `deviceScaleFactor` aren't supported. -- `app.clearState()` isn't supported. -- Saved [sessions](/authentication) aren't supported. - -If the CDP connection drops mid-test, e2e reconnects via `reconnectEndpoint` -(or `cdpEndpoint`) and verifies it's still the same browser. - - -### Downloads on the provider - -Implement `downloads` so `browser.waitForDownload` works on remote browsers. -Because a remote browser writes downloads to its own disk, `downloads` tells -the browser to save files under `dir` and passes each finished path to -`read` to fetch the bytes through the provider's API (see -[Kernel](/integrations/kernel#downloads) or -[Notte](/integrations/notte#downloads)). Without `downloads`, calling -`waitForDownload` on a remote browser fails. Local browser providers don't -need it. - -### Recording on the provider - -Implement `record` to use the service's own recording as the attempt's -video. When an attempt records [video](/reference/config#video), the worker -calls `record` instead of starting the engine's screencast, once the page -is open. The recording covers the whole browser window, tabs and address -bar included. - -`record` returns a `ProviderRecording` from `e2e/engine`. When the attempt -collects its video, its `stop` does one of two things: - -- Writes a file into the directory it gets and returns `{ file }`. e2e keeps - it as `video/` beside the attempt's other artifacts. -- Returns `{ url, mediaType }` for a recording the service keeps. The - report links to it. - - - -```ts title="browser-provider.ts" -import type { ProviderRecording } from 'e2e/engine'; - -// In hostedBrowsers(), beside acquire and release. -async record(lease, context): Promise { - const headers = { Authorization: `Bearer ${context.env['BROWSER_SERVICE_TOKEN'] ?? ''}` }; - const startedAt = new Date().toISOString(); - const started = await fetch(`${options.serviceUrl}/sessions/${lease.id}/recordings`, { - method: 'POST', - headers, - signal: context.signal, - }); - if (!started.ok) throw new Error(`browser service: HTTP ${started.status}`); - const { id } = (await started.json()) as { id: string }; - return { - startedAt, - async stop({ signal }) { - const stopped = await fetch(`${options.serviceUrl}/recordings/${id}/stop`, { method: 'POST', headers, signal }); - if (!stopped.ok) throw new Error(`browser service: HTTP ${stopped.status}`); - // The service keeps the recording; the report links to its player page. - return { url: `${options.serviceUrl}/recordings/${id}`, mediaType: 'text/html' }; - }, - }; -}, -``` - - - -A failed `record` fails the attempt's launch, naming the provider and the -lease. A failed `stop` runs one more time when the attempt ends, so no -recording keeps running on a shared browser. When the service can't record -a browser (a headless one, say), leave `record` out and the engine records -the screencast. [Kernel](/integrations/kernel#recordings) records this way. - -## Icon fonts and generated content - -Text that a stylesheet adds with `::before` or `::after` is part of a -control's name, as screen readers read it: a button with -`.next::before { content: "→" }` is `button "→ Next"`. Label text, as -`getByLabel` reads it, never includes generated content. - -Icon fonts are the exception. Font Awesome and similar fonts draw each icon -from a private-use character (`\f090`), and the engine drops those -characters from every name: - -- `` is - `button "Login"`, and `getByRole('button', 'Login')` finds it. -- A glyph between two words reads as a space. -- A control with only an icon reads as its `title`, when it has one. The - browser still names it by the glyph, so `getByRole` by that title finds - nothing. Give it an `aria-label`, or use - `browser.locator('[title="Sign out"]')`. -- A `RegExp` name matches the browser's name, glyph included, so don't - anchor it: `/Login/`. - -## Inert content - -The agent doesn't see inert content, so it never aims at a control that -takes no input: - -- An element with the `inert` attribute, and everything under it. -- Everything outside a modal ``, opened with `showModal()` or a - `show-modal` command. With several open, only the one shown last stays. - When e2e can't tell which one that is, it leaves out nothing. - -Locators still find inert content, and `toBeVisible` still passes, as in -Playwright. - -## Shadow DOM - -`screen` queries, scopes, and `has` filters reach into open and closed -shadow roots, and the agent sees their content. `first`, `last`, and `nth` -count the matches outside a closed root first, then each root's matches in -order. - -```ts -// The input and the button live in a closed shadow root a widget attached. -await screen.getByPlaceholder('Access code').fill('SHADOW-42'); -await screen.getByRole('button', 'Submit').tap(); -await expect(screen.getByText('Access granted')).toBeVisible(); -``` - -`browser.locator`, `frameLocator`, and `filter({ hasText })` stop at a -closed root. Query the text inside the root instead, or filter with `has`. -A closed root declared in HTML (`