Skip to content
Draft
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
5 changes: 5 additions & 0 deletions .changeset/browser-console-messages.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@e2e-dev/web': patch
---

Add `browser.consoleMessages()` and `browser.pageErrors()` to return the active tab's console messages and uncaught errors.
1 change: 1 addition & 0 deletions .fallowrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"packages/web/tests/types/downloads.ts",
"packages/web/tests/types/app.ts",
"packages/web/tests/types/engine.ts",
"packages/web/tests/types/console-messages.ts",
"packages/mobile/tests/types/options.ts",
"packages/mobile/tests/types/engine.ts",
"packages/desktop/tests/types/engine.ts",
Expand Down
23 changes: 23 additions & 0 deletions apps/testbed/tests/browser.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,29 @@ test.describe('browser fixture', { platforms: ['web'], tags: ['browser'] }, () =
const theme = (await browser.cookies()).find((cookie) => cookie.name === 'theme');
expect(theme?.value).toBe('dark');
});

test('console messages and page errors read back and clear on restart', async ({ app, browser }) => {
// FIXME: the playground doesn't serve /favicon.ico, so headed Chromium and
// hosted Chrome log a 404. Headless runs don't, so that message is
// filtered out to keep the lists the same in every mode.
const logged = async () => (await browser.consoleMessages()).filter((message) => !message.text.startsWith('Failed to load resource'));

await browser.evaluate(() => {
console.error('broken', 42);
void Promise.reject(new Error('rejected'));
setTimeout(() => {
throw new Error('thrown');
});
return null;
});
await expect.poll(async () => (await browser.pageErrors()).map((error) => error.message).toSorted()).toEqual(['rejected', 'thrown']);
expect(await logged()).toEqual([{ type: 'error', text: 'broken 42' }]);

await app.restart();

expect(await logged()).toEqual([]);
expect(await browser.pageErrors()).toEqual([]);
});
});

test('offline fails the page\'s requests and navigations until the test goes back online', { platforms: ['web'], tags: ['browser'] }, async ({ app, screen, browser }) => {
Expand Down
34 changes: 8 additions & 26 deletions apps/web-benchmark/tests/newsletter-signup.e2e.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,21 @@
import { test } from '@e2e-dev/web';
import type { Browser } from '@e2e-dev/web';
import { expect } from 'e2e';

type ConsoleErrorStore = Window & { e2eConsoleErrors?: string[] };

/**
* Hooks `console.error` in the page and returns a reader of what the app has
* logged since. The planted bug's only trace is a console error, and the
* engine has no `browser.onConsole` yet, so the page keeps the list itself.
*/
async function captureConsoleErrors(browser: Browser): Promise<() => Promise<string[]>> {
await browser.evaluate(() => {
const errors: string[] = [];
(window as ConsoleErrorStore).e2eConsoleErrors = errors;
const original = console.error;
console.error = (...args: unknown[]) => {
errors.push(args.map(String).join(' '));
original(...args);
};
return null;
});
return () => browser.evaluate(() => (window as ConsoleErrorStore).e2eConsoleErrors ?? []);
}

test('subscribe renders no feedback and logs a TypeError (planted bug)', async ({ app, screen, browser }) => {
await app.open('/e/newsletter-signup');
const consoleErrors = await captureConsoleErrors(browser);
const email = screen.getByPlaceholder('you@example.com');
await email.fill('maria.novak@example.com');
await screen.getByRole('button', 'Subscribe').tap();

await expect(screen.getByTestId('success-message')).not.toBeVisible();
await expect(screen.getByTestId('error-message')).not.toBeVisible();
await expect(email).toHaveValue('maria.novak@example.com');
await expect.poll(async () => (await consoleErrors()).join('\n')).toContain(
"Cannot read properties of undefined (reading 'subscribe')",
);
await expect.poll(async () => {
const messages = await browser.consoleMessages();

return messages
.filter((message) => message.type === 'error')
.map((message) => message.text)
.join('\n');
}).toContain("Cannot read properties of undefined (reading 'subscribe')");
});
2 changes: 1 addition & 1 deletion docs/migrate/cypress.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ Planned gaps are on the roadmap, and Not yet gaps have no date. Not planned gaps
| `.trigger()`, `cy.scrollTo()` | `hover()`, `dragTo()`, `scrollIntoView()`; for other synthetic events use `browser.evaluate` |
| `cy.intercept({ headers })` and other header matchers | Check `route.request.headers` in the handler, else call `route.fallback()` |
| `cy.wait('@alias')`, `.its('request.body')`, `@alias.all` | Start `browser.waitForResponse(pattern)` before the action; read the request in a `browser.route` handler |
| `Cypress.on('uncaught:exception')` | An app error doesn't fail a test. To fail on one, collect `window.onerror` in `browser.addInitScript`, then assert the list is empty with `browser.evaluate` |
| `Cypress.on('uncaught:exception')` | An app error doesn't fail a test. To fail on one, assert that [`browser.pageErrors()`](/reference/web#pageerrors) is empty |
| `--browser chrome`, `edge`, `electron`, `before:browser:launch` | `web({ browser: 'chromium' })`, or attach to your own Chrome with `web({ connect: { cdpEndpoint } })` |
| `cypress open`, time-travel snapshots | `npx e2e run --headed --watch`, or `--step`; the [trace page](/debugging#traces) shows each step after the run |
| `before()` and `after()` that drive the app, `describe.only` | UI setup in `beforeEach`, cleanup in `afterEach`; sign-in in a top-level `test.setup` that saves a session; `test.only` on each test |
Expand Down
3 changes: 2 additions & 1 deletion docs/migrate/playwright.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ run only in a browser, so a test that uses it declares
| `context.pages()`, `context.newPage()`, `page.bringToFront()` | `browser.tabs()`, `browser.newTab()`, `tab.activate()`; no `context.on('page')` event |
| `page.evaluate(fn, arg)` | `browser.evaluate(fn, arg)`, JSON in and out |
| `page.webmcp.tools()`, `page.webmcp.callTool(name, input)` | the same on `browser.webmcp`, with `web({ webmcp: true })` in place of the launch argument or preferences; the main frame only, see [WebMCP](/reference/web#webmcp) |
| `page.consoleMessages()`, `page.pageErrors()`, `page.on('console')`, `page.on('pageerror')` | Read [`browser.consoleMessages()`](/reference/web#consolemessages) or [`browser.pageErrors()`](/reference/web#pageerrors) after the action. Both return everything since the tab opened, like Playwright's `{ filter: 'all' }`. There are no console or page error listeners |
| `page.addInitScript()`, `page.emulateMedia({ colorScheme, reducedMotion })` | `browser.addInitScript()` or `web({ initScripts })`; `browser.emulateMedia()` |
| `context.addCookies()`, `cookies()`, `clearCookies()` | `browser.setCookies()`, `browser.cookies()`, `browser.clearCookies()` |
| `context.setOffline(true)` | [`browser.setNetwork('offline')`](/reference/web#setnetwork), `'online'` to go back |
Expand Down Expand Up @@ -293,7 +294,7 @@ purpose. Use the workaround, or keep the test in Playwright.
| `waitForResponse(predicate)`, `waitForRequest()`, `page.on('request')`, `response.ok()` | `browser.waitForResponse(pattern)`, or `{ method, url }` to filter on the request's method, then check the response in the test, `status` for `ok()`. For requests, a `browser.route` handler that records `route.request`, then calls `route.fallback()` |
| `route.fulfill({ response })`, `route.abort(code)`, `route.fetch(options)`, `request.postDataJSON()` | `status`, `headers`, and `body` from `route.fetch()`; `JSON.parse(route.request.postData)` |
| `page.addLocatorHandler()` | Dismiss the overlay in `beforeEach`, or set its consent cookie with `browser.setCookies` |
| `page.on('console')`, `page.on('pageerror')`, `page.clock` | A `browser.addInitScript` that records to a `window` array, or that stubs `Date` |
| `page.clock` | A `browser.addInitScript` that stubs `Date` |
| `setGeolocation()`, `grantPermissions()` | A `browser.addInitScript` stub; `app.permissions` on the target |
| `ignoreHTTPSErrors`, `proxy`, `channel`, `launchOptions` | Serve the app over `http`; start the browser yourself and attach with `web({ connect })` |

Expand Down
3 changes: 2 additions & 1 deletion docs/migrate/selenium.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ test('signs in', async ({ app, screen, browser }) => {
| `switchTo().frame()`, `switchTo().alert().accept()` | `browser.frameLocator('#frame')`, `browser.onDialog('accept')` before the action |
| `switchTo().window(handle)`, `getWindowHandles()`, `switchTo().newWindow()` | `tab.activate()`, `browser.tabs()`, `browser.newTab()`; `browser.waitForPopup(() => trigger)` for a tab the app opens, see [Tabs](/reference/web#tabs) |
| `executeScript(script, args)` | `browser.evaluate(fn, arg)`, JSON in and out only |
| `manage().logs().get('browser')` | Read console output with [`browser.consoleMessages()`](/reference/web#consolemessages) and uncaught exceptions with [`browser.pageErrors()`](/reference/web#pageerrors). Reading a list doesn't clear it |
| Page objects | A fixture from `test.extend`, or a goal for `agent.act`, see [Page objects](/page-object-model) |

## What e2e doesn't have yet
Expand All @@ -110,7 +111,7 @@ e2e leaves it out on purpose.
| `ChromeOptions.addArguments`, `setBinary`, `Proxy`, `acceptInsecureCerts` | Start Chrome or Edge with the flags, then attach with `web({ connect })` |
| `@BeforeSuite`, `@AfterSuite`, pytest session-scoped fixtures, WebdriverIO `onPrepare` | Once for the run: the script `app.command` starts, or a wrapper around `e2e run`. Once for a file: `beforeAll` and `afterAll`. Sign-in: a top-level `test.setup` that saves a session |
| BrowserStack or Sauce Labs for web | Your own [browser provider](/browser#write-a-provider), if the vendor has a CDP endpoint |
| `manage().logs()`, request listeners, geolocation | Patch the page in `browser.addInitScript`, record requests in `browser.route` |
| Request listeners, geolocation | Record requests in `browser.route`, stub geolocation in `browser.addInitScript` |
| `setNetworkConditions` | For offline, [`browser.setNetwork('offline')`](/reference/web#setnetwork). No throttling or latency, keep those tests in Selenium |

### Not yet
Expand Down
118 changes: 114 additions & 4 deletions docs/reference/web.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,8 @@ What survives:
read current geometry and focus with `browser.evaluate` before acting.
- Code that uses `surfaceOf(engine)` must read its accessors again after
recovery. Playwright objects it kept belong to the disconnected transport.
- `browser.consoleMessages()` and `browser.pageErrors()` only have entries
from the current document. Chrome doesn't send earlier ones again.

A `browser` provider with `scope: 'attempt'` rides the same persistent
context, with the same limits. The lease's `cdpEndpoint` provisions the
Expand Down Expand Up @@ -481,8 +483,9 @@ export type WebInitScript = string | { readonly path: string } | (() => unknown)

- What reads or acts on a page acts on the active tab: `goto`, `reload`,
`back`, `forward`, `url`, `title`, `waitForURL`, `locator`, `frameLocator`,
`evaluate`, `waitForResponse`, `waitForDownload`, `keyboard`, `mouse`, the
`expect(browser)` matchers, and every `screen` query.
`evaluate`, `consoleMessages`, `pageErrors`, `waitForResponse`,
`waitForDownload`, `keyboard`, `mouse`, the `expect(browser)` matchers, and
every `screen` query.
- What belongs to the browser covers every tab: `cookies`, `setCookies`,
`clearCookies`, `route`, `unroute`, `unrouteAll`, `onDialog`, and
`addInitScript`.
Expand Down Expand Up @@ -515,6 +518,8 @@ export type WebInitScript = string | { readonly path: string } | (() => unknown)
| [`locator`](#locator) | `Locator` |
| [`frameLocator`](#framelocator) | `FrameScreen` |
| [`evaluate`](#evaluate) | `Promise<T>` |
| [`consoleMessages`](#consolemessages) | `Promise<WebConsoleMessage[]>` |
| [`pageErrors`](#pageerrors) | `Promise<WebPageError[]>` |
| [`addInitScript`](#init-scripts) | `Promise<void>` |
| [`route`](#route) | `Promise<void>` |
| [`unroute`](#unroute) | `Promise<void>` |
Expand Down Expand Up @@ -546,7 +551,7 @@ The [config](/reference/config) sets each member's budget:

A `{ timeout }` option overrides the budget on `goto`, `reload`, `back`,
`forward`, `waitForResponse`, `waitForPopup`, `waitForDownload`, and `waitForDownloads`, capped
by the test deadline (`cleanupTimeout` in `afterEach`); `0` waits until it. `url`, `title`, `evaluate`, `addInitScript`, `route`,
by the test deadline (`cleanupTimeout` in `afterEach`); `0` waits until it. `url`, `title`, `evaluate`, `consoleMessages`, `pageErrors`, `addInitScript`, `route`,
`unroute`, `unrouteAll`, `cookies`, `setCookies`, `clearCookies`, `setViewport`,
`emulateMedia`, `setNetwork`, `onDialog`, `newTab`, the `BrowserTab` methods, `keyboard.*`, `mouse.*`, and `webmcp.*` take no override.

Expand Down Expand Up @@ -707,6 +712,106 @@ const title = await browser.evaluate<string>('document.title');
| `ACTION_FAILED` | A Playwright timeout. |
| `ENGINE_FAILURE` | The page closed or the context was lost. |

#### `consoleMessages`

Returns the console messages logged in the active tab since it opened,
oldest first. Only the latest 200 are kept.

```ts
await app.open('/checkout');
await screen.getByRole('button', 'Place order').tap();
await expect(screen.getByText('Order placed')).toBeVisible();
const errors = (await browser.consoleMessages()).filter((message) => message.type === 'error');
expect(errors).toEqual([]);
```

```ts
export interface WebConsoleMessage {
/**
* The message type, such as `'log'`, `'error'`, or `'warning'` (the type of
* `console.warn`). Most values are Playwright's console message types. The
* rest are browser-specific:
*
* - `'verbose'` from browser messages in Chromium
* - `'countReset'`, `'timeLog'`, and `'timeStamp'` from Firefox
* - `'image'` and `''` from WebKit
*/
readonly type:
| 'log' | 'debug' | 'info' | 'error' | 'warning' | 'verbose'
| 'dir' | 'dirxml' | 'table' | 'trace' | 'clear' | 'image'
| 'startGroup' | 'startGroupCollapsed' | 'endGroup' | 'assert'
| 'profile' | 'profileEnd' | 'count' | 'countReset'
| 'time' | 'timeLog' | 'timeEnd' | 'timeStamp' | '';
/** The message text. */
readonly text: string;
}
```

- Messages from the tab's frames and dedicated workers are included.
Messages from service workers aren't.
- Browser messages are included, such as Chromium's
`Failed to load resource` on a 404. If the app doesn't have a favicon,
headed Chromium and hosted Chrome request `/favicon.ico` and log a 404.
Headless runs don't.
- The list isn't cleared on navigation, so messages from earlier documents
in the tab stay in it.
- After `app.restart()`, the list only has messages from the new page.
- Each tab has a separate list. Activate a tab to read its list.
- A message can show up in the list shortly after it's logged. To wait for
one, use [`expect.poll`](/reference/expect#polling-a-value). As in the
example, wait for the result on screen before asserting the list is empty.

<Note>
On a [persistent context](#recovering-a-cdp-transport), the first tab is
reused. Its `consoleMessages` and `pageErrors` entries from before the
attempt are dropped, while init script entries are kept. After a CDP
reconnect, the lists only have entries from the current document.
</Note>

| Throws | When |
| --- | --- |
| `APP_NOT_OPEN` | No page is open yet. |
| `ACTION_FAILED` | Timed out after [`actionTimeout`](/reference/config#actiontimeout). |
| `ENGINE_FAILURE` | The browser connection was lost. |

#### `pageErrors`

Returns the uncaught errors and unhandled promise rejections in the active
tab since it opened, oldest first. Only the latest 200 are kept.

```ts
await app.open('/checkout');
await screen.getByRole('button', 'Place order').tap();
await expect(screen.getByText('Order placed')).toBeVisible();
expect(await browser.pageErrors()).toEqual([]);
```

```ts
export interface WebPageError {
/** The error name, such as `'Error'` or `'TypeError'`. */
readonly name: string;
/** The error message, as the browser reports it. */
readonly message: string;
/** The stack trace, as the browser reports it, or `''` when there isn't one. */
readonly stack: string;
}
```

- The browser's error text is split at its first colon into `name` and
`message`, matching Playwright. So a rejected `'Request failed: 500'`
has the name `'Request failed'` and the message `'500'`. A value without
a colon has the name `''`.
- Errors from the tab's frames are included, along with dedicated worker
errors in Chromium.
- Navigation, `app.restart()`, other tabs, late entries, and persistent
contexts work the same way as in [`consoleMessages`](#consolemessages).

| Throws | When |
| --- | --- |
| `APP_NOT_OPEN` | No page is open yet. |
| `ACTION_FAILED` | Timed out after [`actionTimeout`](/reference/config#actiontimeout). |
| `ENGINE_FAILURE` | The browser connection was lost. |

#### `route`

Adds an attempt-scoped network route.
Expand Down Expand Up @@ -1362,7 +1467,8 @@ The package exports these types for typing config helpers and fixtures:
`BrowserReleaseContext`, `BrowserProviderDownloads`,
`BrowserDownloadContext`, `PlaywrightLiveSurface`, `Browser`, `FrameScreen`,
`BrowserExpectation`, `WebRoute`, `RouteFulfillResponse`,
`RouteContinueOverrides`, `RouteMatcher`, `WebResponse`, `Cookie`, `CookieFields`,
`RouteContinueOverrides`, `RouteMatcher`, `WebResponse`, `WebConsoleMessage`,
`WebPageError`, `Cookie`, `CookieFields`,
`CookieFilter`, `Dialog`, and `DialogHandler`.

The runtime exports are `web`, [`surfaceOf`](#surfaceof), and `test`,
Expand Down Expand Up @@ -1521,6 +1627,10 @@ export interface Browser extends Expectable<BrowserExpectation> {
fn: string | ((arg: Arg) => T | Promise<T>),
arg: Arg,
): Promise<T>;
/** Returns the console messages logged in the active tab since it opened. Only the latest 200 are kept. */
consoleMessages(): Promise<WebConsoleMessage[]>;
/** Returns the uncaught errors and unhandled rejections in the active tab since it opened. Only the latest 200 are kept. */
pageErrors(): Promise<WebPageError[]>;
/** Adds a script every document runs before the page's own, from the next navigation on. */
addInitScript(script: string | { path: string } | (() => unknown)): Promise<void>;
/** Adds an init script function called with one JSON argument. */
Expand Down
7 changes: 6 additions & 1 deletion packages/web/src/attempt-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -314,14 +314,19 @@ export class AttemptSession {
* of a second tab beside it, which a hosted browser's live view and
* recording would show behind the test's. The tab is navigated to
* `about:blank` first, so its document runs the context's init scripts
* as a new tab's does. Every later page is a new tab.
* as a new tab's does. Before that navigation, its console messages and
* page errors are cleared because Chrome replays earlier ones to every new
* CDP client. Clearing them after would drop the init scripts' entries from
* `about:blank`. Every later page is a new tab.
*/
private async nextPage(context: BrowserContext): Promise<Page> {
const first = this.firstPage;
this.firstPage = false;
if (first && this.options.persistent !== undefined) {
const initial = context.pages().find((page) => !page.isClosed());
if (initial !== undefined) {
await initial.clearConsoleMessages();
await initial.clearPageErrors();
await initial.goto('about:blank');
return initial;
}
Expand Down
Loading
Loading