Page events as an extra check
Page and BrowserContext emit events that expose what the UI does not show. These are pageerror for unhandled exceptions, console for the console, response for 404 and 500 statuses. Subscribe before the action, because an event that has passed is lost to the code. A response with an error status is not requestfailed: that event covers only network-level failures.
Playwright · Browser, Context, Page
The UI assertions are green, yet the console is red. How can a test see what is not on screen?
The payment test passed: the button was clicked, the confirmation is on screen. Yet the browser console shows an unhandled exception, a third-party script answered 500, and the analytics load was cut off. The user does not see this until something nearby breaks. Page and BrowserContext emit events you can subscribe to, and that is how a test gets access to everything that happens outside the visible UI. This lesson covers which events there are, when to subscribe, and how to make the check automatic.
How it works and why. Playwright watches the page through the browser protocol and delivers every event (a console message, a network request, a dialog) to the Node.js test process. An event does not wait for the test: it arrives when it happens, and if there is no handler at that moment, it is simply lost to your code. Hence two rules. Subscribe before the action that triggers the event. And remember that events arrive asynchronously, so check what you collected only after the UI has reached the expected state.
Page events: console, pageerror, request, response, requestfailed, requestfinished, dialog, popup, download, filechooser, websocket, frameattached. Many of them exist at the BrowserContext level for all pages at once, plus the page event for new tabs.
| What happened | Which event |
|---|---|
| Unhandled exception in the page's JS | pageerror |
The code itself called console.error() | console, type error |
| A request failed at the network level (reset, CORS, DNS) | requestfailed |
| The server answered 404 or 500 | response with a status |
| alert, confirm, prompt | dialog |
| A new tab from the page | popup |
| A file download | download |
An important limit: a 404 or 500 response is not a requestfailed. The request finished successfully, just with an error status, so you catch it through response.
When to check the collected errors
Example: the UI is green, the errors are invisible. The first version of the test checks only the screen:
// before: checking only what is visible
test('payment goes through', async ({ page }) => {
await page.goto('/checkout');
await page.getByRole('button', { name: 'Pay' }).click();
await expect(page.getByText('Thank you for your order')).toBeVisible();
});
The test is green although after the click the page threw a TypeError in the script that sends an analytics event, and the reviews widget answered 500. The UI assertion knows nothing about it. Subscribing to events fixes that:
// after: collect problems and check them after waiting for the UI
test('payment goes through without JS errors and 5xx', async ({ page }) => {
const problems: string[] = [];
page.on('pageerror', (err) => problems.push('pageerror: ' + err.message));
page.on('console', (msg) => {
if (msg.type() === 'error') problems.push('console: ' + msg.text());
});
page.on('requestfailed', (req) => problems.push('failed: ' + req.url()));
page.on('response', (res) => {
if (res.status() >= 500) problems.push(res.status() + ' ' + res.url());
});
await page.goto('/checkout');
await page.getByRole('button', { name: 'Pay' }).click();
await expect(page.getByText('Thank you for your order')).toBeVisible();
expect(problems).toEqual([]);
});
How to read it. pageerror is an exception nobody caught, while console with type error is what the code itself printed through console.error. The second stream is often noisy: trackers, extensions, third-party widgets. So the array is usually filtered for known noise, and the test fails only on what belongs to the product. The assertion on the empty array comes after toBeVisible, not right after click() (figure 1).
Events that demand a reaction. Some events are not just observed, they block the page. If there is no dialog handler at all, alert, confirm and prompt are dismissed automatically. If there is one, it must call accept() or dismiss() itself, or the page will hang. A new tab and a download are awaited through waitForEvent, creating the promise before the click:
let message = '';
page.once('dialog', async (dialog) => {
message = dialog.message();
await dialog.accept();
});
await page.getByRole('button', { name: 'Delete' }).click();
expect(message).toContain('Delete the record?');
const downloadPromise = page.waitForEvent('download');
await page.getByRole('button', { name: 'Export CSV' }).click();
const download = await downloadPromise;
expect(download.suggestedFilename()).toBe('orders.csv');
Check the dialog text outside the handler: an exception inside an event handler does not always stop the test the way you expect.
An auto fixture instead of copying. To avoid duplicating the collection in every test, move it into a fixture with auto: true: it runs for every test by itself, subscribes at the start and checks the result in teardown:
import { test as base, expect } from '@playwright/test';
export const test = base.extend<{ jsErrors: void }>({
jsErrors: [
async ({ page }, use) => {
const errors: string[] = [];
page.on('pageerror', (err) => errors.push(err.message));
await use();
expect(errors, 'unhandled JS errors on the page').toEqual([]);
},
{ auto: true },
],
});
Subscribing before or after the action
After the action
click(), then page.on('dialog') or waitForEvent. The event already happened with no handler: the dialog closed by itself, and waitForEvent waits until the timeout.
Before the action
First the handler or the waitForEvent promise, then click(). The event is guaranteed to reach the test code.
Limits and alternatives. Collecting events shows symptoms, not the cause: to see what happened on the page before a failure, look at the trace. A console subscription sees only the page's console, not server logs. A hard "no console errors" rule for a whole page makes the test depend on third-party scripts, so combine it with an allow-list of known exceptions. For the network, when you need to replace or block rather than observe, use page.route() (a separate topic). In Cypress similar things go through cy.on('uncaught:exception'), which by default fails the test on any unhandled exception, while Playwright has no such behaviour and you add it yourself.
Common mistakes.
- Subscribing after the action that triggers the event: the event has already happened,
waitForEventhangs until the timeout, and the dialog was closed automatically. - Asserting the error array right after a click without waiting for the UI state: a late error slips through.
- Expecting
requestfailedto fire on HTTP 500: that is aresponseevent with a status. - Not filtering third-party noise: the test fails for reasons unrelated to the product.
- Adding a
dialoghandler and not callingaccept()ordismiss(): the page waits for an answer and hangs.
Check yourself
A test does click(), immediately expect(errors).toEqual([]), and only then waits for the confirmation text. A JS error arrives 200 ms after the click. What will the test show and how do you fix it?
Answer
The array is still empty, so the check passes, and the error appears after it and stops nobody. First wait for the UI state (toBeVisible), and only then assert the array. Then the event will almost certainly have arrived.
The server returned 502 for a third-party widget. Will page.on('requestfailed') fire, and which event do you need?
Answer
No. The request finished successfully, just with status 502, while requestfailed describes a network-level failure: a reset, a block, DNS. Check the status in a response handler through res.status().
pageerror and console to see JS errors that UI assertions do not catch, and I wait for dialogs, new tabs and downloads through a handler or a waitForEvent created before the click. Middle/Senior: I move error collection into an auto fixture that checks for an empty array after the test, with a filter for known noise. I catch error statuses through response, because requestfailed does not see them. I place the assertion after waiting for the UI, because events arrive asynchronously.