QA Interview Hub · Knowledge base · Quizzes · Українська

Playwright

Interaction: actions, tabs, frames, files, dialogs

Actions on elements: what to use when

The action method is chosen by the browser events the app listens to. Ordinary fields are filled by fill with a single input event, while pressSequentially types key by key (keydown, keypress, input, keyup) for autocomplete, masks and debounced search. check beats click because it is idempotent and verifies the final state, and force: true hides a real defect.

Playwright · Interaction

The city field is filled but no autocomplete suggestions appear. fill worked, so why is the app silent?

A test types "Lv" into the city field and waits for the suggestion list. The value is in the field, the screenshot confirms it, yet the list never shows up and the test fails on the assertion. The test is not broken: it "talks" to the page differently from a person. The input method was picked for convenience, not for the events the app is waiting for. This article is about choosing the action method: what each one really does to the page and where the difference hides.

How it works and why. Every action (click, fill, check…) has two parts. First the locator finds the element, waits for actionability (visible, stable, enabled, not covered) and scrolls it into view if needed. Then the action itself runs, and Playwright waits for any navigations it started. The methods differ in the second part: they produce different sets of browser events, and the app reacts to events, not to "the value in the field".

fill focuses the field, clears it and inserts the value in one step, sending a single input event. It is fast and independent of the keyboard layout, so fill is the standard for ordinary inputs, textarea and contenteditable. pressSequentially types character by character: every key gets the full keydown → keypress → input → keyup cycle. It is needed where the logic hangs on keys: autocomplete, phone or card masks, debounced search. The old type is deprecated and was replaced by pressSequentially.

What the app sees in an autocomplete field

Typical

fill('Lv')

The value lands in the field in one step, with a single input event. keydown and keyup handlers are not called, so autocomplete never starts.

Better

pressSequentially('Lv')

Each letter goes through the full key event cycle, like a person typing. Autocomplete, masks and debounce work as they do for a user.

Figure 1. The value in the field is the same, but the set of events differs. The app reacts to events, not to the value.

Example: autocomplete that does not "hear" fill. The city field fires a suggestions request on every key press. A test written out of habit:

// before: the field is filled, but the suggestions never appear
await page.getByLabel('City').fill('Lv');
await expect(page.getByRole('option', { name: 'Lviv' })).toBeVisible(); // timeout

The failure looks like a waiting problem, and the first reaction is usually to raise the timeout or add a pause. That will not help, because the event that starts the search never happened. The clue is that the value in the field is right while nothing reacts to it. The fix: send the keys.

// after: the app sees real key presses
await page.getByLabel('City').pressSequentially('Lv');
await page.getByRole('option', { name: 'Lviv' }).click();

// a slow mask or a field that drops fast input: add a delay per key
await page.getByLabel('Phone').pressSequentially('501234567', { delay: 50 });

// a single key or a chord
await page.getByLabel('Search').press('Enter');
await page.getByLabel('Notes').press('ControlOrMeta+A');

Why this is right and "paste the text and poke the field" is wrong: the test reproduces the user's path, and if the key handler breaks in the app, the test will show it. The delay option is rarely needed: a debounced field waits for a pause after the last key, so fast typing does not hurt it. Add a delay only when the app truly drops fast input, and only for that reason.

Choices and toggles. check and uncheck do not just click: after the click they verify that the state really changed and throw if not (for example, a handler cancelled the change). If the checkbox is already in the wanted state, the action does nothing, so the test is idempotent. setChecked(bool) is handy in parameterised tests. selectOption works only with a native select: by value, label, index, or an array for multiple. A custom dropdown is made of ordinary divs, so it is opened with a click on the combobox and the option is picked through getByRole('option'). For date and time fields fill expects the format of the input type (yyyy-mm-dd, HH:mm, yyyy-MM-ddTHH:mm), not the user's locale.

A checkbox: click or check

Typical

click()

Just presses. If the checkbox is already checked (left over from a previous scenario), the click clears it. Nobody verifies the state after the click.

Better

check()

Sets the wanted state: an already checked box is left alone. After the click it verifies the result and fails if the state did not change.

Figure 2. For checkboxes and radio buttons the method should express the intent "must be checked", not "press".
await page.getByRole('checkbox', { name: 'Accept terms' }).check();
await page.getByRole('checkbox', { name: 'Newsletter' }).setChecked(false);
await page.getByLabel('Currency').selectOption({ label: 'UAH' });
await page.getByLabel('Tags').selectOption(['qa', 'ci']); // <select multiple>

// custom dropdown built from divs: a click, not selectOption
await page.getByRole('combobox', { name: 'Country' }).click();
await page.getByRole('option', { name: 'Ukraine' }).click();

// date inputs take the format of the input type, not of the locale
await page.getByLabel('Date').fill('2026-10-08'); // type="date"
await page.getByLabel('Time').fill('14:30'); // type="time"

Mouse and drag. Every click moves the cursor to the element automatically, so a separate hover is needed only for menus that open on hover and for tooltips. click options: button, modifiers, position (a point inside the element), clickCount, delay. force: true skips the actionability checks, so it hides real problems such as overlap or a disabled element, and stays a last resort. trial: true runs all the checks but does not perform the action. dragTo is enough for most drag-and-drop, and for libraries that listen to intermediate mousemove events the drag is assembled by hand with page.mouse and the steps option.

await page.getByRole('menuitem', { name: 'Products' }).hover();
await page.getByRole('link', { name: 'Laptops' }).click();

await page.getByRole('row', { name: 'Order 42' }).click({ button: 'right' });
await page.getByRole('row', { name: 'Order 42' }).click({ modifiers: ['Shift'] });
await page.getByRole('cell', { name: 'Amount' }).dblclick();

// check that the click would be possible, without doing it
await page.getByRole('button', { name: 'Pay' }).click({ trial: true });

// drag and drop: the simple way
await page.getByTestId('card-1').dragTo(page.getByTestId('column-done'));

// the manual way, for libraries that listen to mousemove
const handle = await page.getByTestId('slider-handle').boundingBox();
if (!handle) throw new Error('handle is not visible');
await page.mouse.move(handle.x + handle.width / 2, handle.y + handle.height / 2);
await page.mouse.down();
await page.mouse.move(handle.x + 200, handle.y + handle.height / 2, { steps: 10 });
await page.mouse.up();
TaskMethodWhy
Ordinary fieldfillfast, one input event
Autocomplete, mask, debouncepressSequentiallythe app listens to every key
Enter, Tab, Ctrl+Apressone key or a chord
Checkbox, radiocheck / setCheckedverifies the final state
Native selectselectOptionby value, label or array
Custom dropdownclick + getByRole('option')they are ordinary elements
Hover menuhover + clickthe item does not appear without hover

Limits and alternatives. press with ControlOrMeta becomes Control on Windows and Linux and Meta (Cmd) on macOS, so one test works on every OS. All these methods model a user rather than push a value into the app, so if you only need to prepare state (for example, open a form with the fields already filled), it is faster to do that through the API or storageState than through the UI. In Cypress type types key by key by default, so "paste in one step" is a separate choice there; in Playwright it is the other way round: fast fill by default, and key-by-key typing has to be chosen on purpose. In Selenium sendKeys also sends keys, so the habit "always type" carries over to Playwright as pressSequentially everywhere, which brings slowness.

Common mistakes.

  • pressSequentially everywhere "just in case": tests get slower with no gain when the field does not listen to keys.
  • fill where the app listens to keys: the value is there, the suggestions or mask are not, and the test fails with a vague cause.
  • click on a checkbox instead of check: the test will not notice that the state did not change, and a rerun on an already checked box clears it.
  • force: true instead of finding out why the element is covered: the test passes while a real user could not press the button.
  • A locale-style date (08.10.2026) in fill for type="date": a format error.
  • selectOption on a custom dropdown: it has no select tag.

Check yourself

After fill('Lv') the city value is right, but the suggestion list does not appear. Will waitForTimeout(2000) before the assertion help?

Answer

No. The key event the autocomplete waits for never happened, so no matter how long the test waits, the search does not start. You need pressSequentially, which sends keydown, keypress, input and keyup, not a pause.

A checkbox stayed checked from the previous scenario. What happens after click() and what after check()?

Answer

click() clears it, because it just presses, and the test goes on with the wrong state. check() sees that the box is already checked and does nothing; otherwise, after the click, it verifies that the state became "checked".

A test with click({ force: true }) on "Pay" is green, yet users complain the button does not respond. Why, and how do you find the cause?

Answer

force skips the "receives events" check, so the click goes to the button's coordinates even though a banner or modal covers it. Remove force and read the failure log: it names the element that intercepts events. Then close it like a user would, or fix the layout.

In an interview. Junior: For ordinary fields I use fill, for a native select selectOption, for checkboxes check. I open a custom dropdown with a click and pick the option by role. Middle/Senior: I choose the method by the events the app listens to: pressSequentially only for autocomplete, masks and debounced search, because fill does not fire keydown/keyup. check beats click because it is idempotent and verifies the final state. I treat force: true as a smell: first I find what covers the element, otherwise the test goes green where a user would be stuck.

New tabs, popups and iframes

A new tab is a new Page in the same BrowserContext, and the popup event fires once and is not stored. So the waitForEvent promise is created before the click and awaited after it. An iframe is a separate document that an ordinary locator does not see, so it is entered through frameLocator, which works with cross-origin frames too.

Playwright · Interaction

A click opened a new tab, yet the test waits for it until the timeout. Has the event already passed?

The "Contract" link opens in a new tab. The test clicks, then writes await page.waitForEvent('popup'), and 30 seconds later it fails with a timeout, even though in the video the tab opened at once. Another test types a card number into a payment widget and cannot find the field: it is visible on the screen, yet the locator "sees nothing". Both problems share a root: a new tab and an iframe live in their own "spaces", and Playwright has to be told to go there explicitly. Below: how this is built, why the order "listener, click, await" is not negotiable, and how to enter an iframe.

How it works and why. A new tab in Playwright is a new Page in the same BrowserContext: it shares cookies and storage with the opener, so the login is kept. Playwright emits the event about the new page once, at the moment the browser creates it. It is an ordinary event emitter with no "memory": whoever did not subscribe in advance does not get the event and cannot read it later. A click runs fast, and by the time the test reaches the next line the event has already passed. Hence the rule: create the promise before the click and await it after.

The popup event fires once the tab has navigated to its initial URL, but the document may still be loading. Locators and web-first assertions (toHaveURL, element visibility) wait on their own, so waitForLoadState() is rarely needed: before steps that do not auto-wait, such as evaluate.

Order of steps when a tab opens

CorrectWrong 1 create promise 2 click 3 await promise popup in hand,test goes on 1 click event: no listener 3 create promise waits for a newevent to timeout
Figure 1. The event arrives once, at the moment of the click. The listener must exist before that moment, otherwise there is nothing to read it from.

Example: from a hang to a stable test. A test written "in sequence", the way it reads:

// before: the listener is created after the click
await page.getByRole('link', { name: 'Contract' }).click();
const popup = await page.waitForEvent('popup'); // may wait until the timeout
await expect(popup).toHaveURL(/contract/);

There is no log with an answer here: the test just waits until the timeout and fails with a message about waiting for the popup event. That very lack of a hint gives the cause away: the event happened, but there was no listener at that moment. The correct version:

The tab listener: what each line does

1const popupPromise =
  page.waitForEvent('popup');
2await page
  .getByRole('link', {
    name: 'Contract',
  })
  .click();
3const popup = await popupPromise;
await popup.waitForLoadState();
4await expect(popup).toHaveURL(
  /contract/,
);
await expect(
  popup.getByRole('heading', {
    name: 'Contract',
  }),
).toBeVisible();
  1. Subscribe: the event listener is created before the click. It is a promise nobody awaits yet.
  2. Action: the click opens the tab, and the event is already being listened to.
  3. Wait: await waits for the event and returns the new page.
  4. Assertion: the URL is checked on the new tab.
Figure 2. The numbers lead to the explanations of the code lines.

page.waitForEvent('popup') catches tabs opened from a specific page (window.open, target="_blank"). context.waitForEvent('page') catches any new page of the context, including one opened by another tab. The Promise.all variant is also correct, because the listener is created before the click. Do not "simplify" the test by removing target="_blank" in the DOM: then it no longer checks the real behavior.

// any new page of the context, not only one opened by this page
const [newPage] = await Promise.all([
  context.waitForEvent('page'),
  page.getByRole('button', { name: 'Open report' }).click(),
]);
await newPage.waitForLoadState('domcontentloaded');

// every page in the context, e.g. to check how many tabs are open
expect(context.pages()).toHaveLength(2);

Iframe. An iframe is not a separate page but a separate document inside a page. Ordinary locators search the main document and do not go into a frame, so page.getByText(…) will not find text that is visible on the screen. An explicit step is needed: frameLocator returns an object on which you call the usual getByRole, getByLabel, and so on. locator.contentFrame() does the same from the locator of the iframe element, and the way back is frameLocator.owner(). Both are lazy like locators: they wait until the frame appears and loads, so no sleep is needed.

Where a locator searches

Typical

page.getByRole('button', { name: 'Pay' })

Searches the main document. The button inside the iframe is visible on screen, but to the locator it does not exist: "element not found".

Better

page.frameLocator('#payment-iframe').getByRole(…)

First enters the iframe's document, then searches in it. Waits until the frame appears and loads.

Figure 3. "Visible on screen" does not mean "in this document". A forgotten step into the frame is the most common reason an element seems to vanish.
const card = page.frameLocator('#payment-iframe');
await card.getByLabel('Card number').fill('4242424242424242');
await card.getByRole('button', { name: 'Pay' }).click();

// the same through a locator of the iframe element
const frame = page.locator('#payment-iframe').contentFrame();
await expect(frame.getByText('Payment accepted')).toBeVisible();

// nested frames: a chain
const inner = page.frameLocator('#outer').frameLocator('#inner');
await inner.getByRole('button', { name: 'Confirm' }).click();

// the iframe element itself lives in the main document
await expect(page.locator('#payment-iframe')).toBeVisible();

Cross-origin frames, such as a payment widget from another domain, work the same way, because Playwright drives the browser from outside and not from the page's JavaScript, so the same-origin policy does not apply to it.

Limits and alternatives. The old page.frame({ name }) returns a Frame object with methods like frame.locator. It does not wait and returns null if the frame is not there yet, so frameLocator is better for new tests. In Selenium an iframe needs switchTo().frame(), and afterwards all commands go into that frame until you switch back: easy to forget to leave. In Playwright the step is local to a single locator, so there is no "current frame". In Cypress iframe support is limited: a same-origin frame can be queried through its document, but there is no command to switch into a frame, so a plugin is often used. A new tab in Cypress does not work like in Playwright either: the test stays in one tab. Playwright's strong side is that a tab is a full Page that you work with like the main one.

Common mistakes.

  • A click before waitForEvent: the event is missed and the test waits until the timeout.
  • Working with the popup without waitForLoadState or an assertion: the first check sees an empty page.
  • A main-page locator for an element inside an iframe.
  • Your own setTimeout waits for the frame to appear instead of the lazy frameLocator.
  • Forgotten open tabs: each test gets a new context, so they usually do not interfere, but in a shared context they must be closed.

Check yourself

A test first does click() on a link, and the next line is await page.waitForEvent('popup'). In the video the tab opens, yet the test fails with a timeout. Why?

Answer

The popup event arrived during the click, when there was no listener, and Playwright does not keep past events. The next waitForEvent waits for a new event that never comes. Create the promise before the click (const p = page.waitForEvent('popup')), click, and then await p, or use Promise.all.

The payment form is visible on screen, but page.getByLabel('Card number') does not find the field. What do you do, and does it matter that the frame is from another domain?

Answer

The field lives in another document, so enter the frame: page.frameLocator('#payment-iframe').getByLabel('Card number'). The other domain does not matter: Playwright drives the browser from outside, and the same-origin policy does not apply to it.

A test opens a popup and immediately reads await popup.title(), but sometimes gets an empty title. Which line do you add and why?

Answer

At the moment of the event the tab's document may still be loading. Add await popup.waitForLoadState() or rely on a web-first assertion such as expect(popup).toHaveURL(…), which retries until the page has loaded.

In an interview. Junior: For a new tab I first create the waitForEvent('popup') promise, then click, then await the promise. For an iframe I use frameLocator. Middle/Senior: The event arrives once and is not stored, so the listener must exist before the click, otherwise the test hangs until the timeout. A new tab belongs to the same context and shares cookies. An iframe is a separate document, so an ordinary locator does not see into it. frameLocator is lazy and works with cross-origin frames because Playwright drives the browser from outside. Unlike Selenium there is no "current frame" that is easy to forget to reset.

File uploads and downloads

Files are uploaded with setInputFiles on a file input without the OS dialog, and a dynamic file picker is caught with the filechooser event. Downloads are caught with the download event, with the promise created before the click. The temporary file disappears with the context, so it is saved with saveAs. Check the content, not just the name: header, row count, totals.

Playwright · Interaction

The CSV export "worked", yet the file has only a header. Why did the test not notice?

The "Export" button is clicked, the browser hands over a file with the right name transactions.csv, and the test is green. Then accounting opens the file and sees only the header row: a query failure made the report empty. The test checked the name and left the content unchecked. Files in a browser are a separate class of actions: the system file-picker dialog is not available to automation, and downloads land in a temporary folder that the browser cleans itself. Playwright avoids both problems by working with browser events instead of OS windows. Below: how upload and download are built and what to check in them.

Upload: how it works. The main method is setInputFiles on an input type="file" element. It works even if the input is hidden behind a nice button (getByLabel finds it by its label), and it does not open a real OS dialog: Playwright puts the files straight into the element, as the browser would after a selection. You can pass a path, an array of paths for multiple, or an object { name, mimeType, buffer }: the file is created right in the test with no binaries in the repository, which is handy for edge cases (a huge file, a forbidden extension, empty content). An empty array clears the selection. Relative paths are resolved from the current working directory (usually the project root), not from the test file.

await page.getByLabel('Document').setInputFiles('fixtures/passport.pdf');
await page.getByLabel('Documents').setInputFiles(['fixtures/a.pdf', 'fixtures/b.pdf']);

// a file generated in the test: no binary in the repository
await page.getByLabel('Statement').setInputFiles({
  name: 'report.csv',
  mimeType: 'text/csv',
  buffer: Buffer.from('id,amount'),
});

// negative test: a file above the limit of the form
await page.getByLabel('Document').setInputFiles({
  name: 'big.pdf',
  mimeType: 'application/pdf',
  buffer: Buffer.alloc(11 * 1024 * 1024),
});
await expect(page.getByRole('alert')).toContainText('10 MB');

await page.getByLabel('Document').setInputFiles([]); // clear the selection

If there is no input in the DOM and a button opens the dialog dynamically (for example via input.click() in JavaScript), you catch the filechooser event. It is the same scheme as with a new tab: listener before the click, await after. setInputFiles also works for directories (webkitdirectory). After an upload you check not only that "the file name appeared" but also the backend's reaction: processing status, preview, validation error message.

// there is no input in the DOM: a button opens the system dialog
const chooserPromise = page.waitForEvent('filechooser');
await page.getByRole('button', { name: 'Upload photo' }).click();
const chooser = await chooserPromise;
expect(chooser.isMultiple()).toBe(false);
await chooser.setFiles('fixtures/photo.png');

Download: how it works. A download starts with a click, so the download event is listened for in advance, by the same "promise before the click" rule. The Download object gives suggestedFilename(), url(), failure() (an error text or null), path() and saveAs(). The browser downloads the file into a temporary folder, and when the context closes, the file is deleted. So to keep it as an artifact you need saveAs, and the best place is testInfo.outputPath: isolated between tests and workers, and the folder is cleaned up together with the results.

The life of a downloaded file

1 waitForEvent('download') 2 click "Export" 3 file in a temporary folder saveAs into thetest's outputPath:read the content,check it context closed:the temporary fileis deleted, thecontent is gone
Figure 1. The temporary file lives only while the context lives. Anything you need to check or keep is done before it closes.

Example: from checking the name to checking the content. The initial version, which "passed" an empty report:

// before: the name is checked, the content is not
const downloadPromise = page.waitForEvent('download');
await page.getByRole('button', { name: 'Export CSV' }).click();
const download = await downloadPromise;
expect(download.suggestedFilename()).toBe('transactions.csv'); // an empty file passes too

Its weakness is that the names match even for an empty file. The fixed version saves the file to outputPath, reads it and checks the header and the row count:

import { readFile } from 'node:fs/promises';

test('export of transactions', async ({ page }, testInfo) => {
  await page.goto('/transactions');

  const downloadPromise = page.waitForEvent('download');
  await page.getByRole('button', { name: 'Export CSV' }).click();
  const download = await downloadPromise;

  expect(download.suggestedFilename()).toBe('transactions.csv');
  expect(await download.failure()).toBeNull();

  const filePath = testInfo.outputPath(download.suggestedFilename());
  await download.saveAs(filePath);
  const rows = (await readFile(filePath, 'utf-8')).trim().split(/\r?\n/);
  expect(rows[0]).toBe('id,date,amount,currency');
  expect(rows.length - 1).toBe(25);
});

What we check in a downloaded file

Typical

Only suggestedFilename()

An empty file, a truncated report or a file in the wrong encoding has the right name. The test is green, the defect is in production.

Better

Name, failure, content

failure() is null, and the CSV has the right header, row count and totals. The test catches exactly what would break a user.

Figure 2. The file name is the minimum. The real value is in the content.

What to check in the content. The CSV header, the row count, totals, encoding (BOM, delimiter, date format). For CSV readFile and a split into lines is enough; for XLSX or PDF you add libraries (exceljs, pdf-parse), and for a quick check of the file type its signature is enough. A big file is read as a stream:

const download = await downloadPromise;
const stream = await download.createReadStream(); // alternative to saveAs
const chunks: Buffer[] = [];
for await (const chunk of stream) chunks.push(chunk as Buffer);
const body = Buffer.concat(chunks);

expect(body.subarray(0, 5).toString()).toBe('%PDF-'); // the file is really a PDF
expect(body.length).toBeGreaterThan(1000);

In fintech such checks are part of the requirements: statements and reports for accounting must match what the user sees, down to the cent.

Limits and alternatives. Playwright hands you the downloaded file but does not open it in an app: for a PDF it gives bytes, not a rendered page, so "does the PDF look right" cannot be verified this way. In Selenium there is no download event: the file appears in the browser's folder and the test waits for it on disk by polling, which is slower and more fragile. In Cypress a download also lands in a folder (downloadsFolder) and is read with cy.readFile. The key advantage of Playwright is the download event with a ready object and isolation between workers.

Common mistakes.

  • Clicking "Export" without a prior waitForEvent('download'): the event is missed and no download is received.
  • Checking only suggestedFilename() without the content: an empty file with the right name passes.
  • Saving to an arbitrary folder (./downloads): parallel workers overwrite each other's files and CI is left with junk.
  • Binary fixtures in the repository for every edge case instead of generating them through buffer.
  • Finding the input by the button's CSS class instead of getByLabel: breaks when the design changes.

Check yourself

The test from the first example passes an export that contains only the header row. Why, and which lines of the fixed version catch such a file?

Answer

The first example has only suggestedFilename(): the name is right even for an empty file. In the fixed version expect(rows.length - 1).toBe(25) counts the data rows: an empty report gives 0 and the test fails. expect(rows[0]) additionally checks the header itself.

At the end of a test the downloaded file is needed as an artifact, but it turns out to be gone. Why, and what do you do?

Answer

A downloaded file lives in a temporary folder and is deleted when the context closes. Save it inside the test with download.saveAs(testInfo.outputPath(…)) while the context is alive. That folder is isolated between workers, so parallel tests do not overwrite each other.

The form has no input type="file" in the DOM, and the "Upload photo" button opens the system dialog. Which method do you use, and in what order?

Answer

The filechooser event: create page.waitForEvent('filechooser') before the click, click, await the promise and call chooser.setFiles(…). The order is the same as for popup and download: listener before the action.

In an interview. Junior: For upload I use setInputFiles, and for download I create the waitForEvent('download') promise before the click and check the file. Middle/Senior: I do upload through setInputFiles, often with a buffer to generate edge-case files in the test, and if the dialog opens dynamically I catch filechooser. I save a download with saveAs into testInfo.outputPath, because the temporary file disappears with the context and a shared folder breaks on parallel workers. I check not only the name but also the content: header, row count, totals and encoding.

alert, confirm and prompt dialogs

Playwright automatically dismisses the native alert, confirm and prompt dialogs when nobody listens to the dialog event. Then confirm returns false, while beforeunload is accepted instead. If a listener exists, the auto-close is off and it must call accept() or dismiss() in every branch, otherwise the action stalls. HTML modals are not browser dialogs and are found like ordinary elements, for example with getByRole('dialog').

Playwright · Interaction

I press "Delete", see no confirmation, and the account is still there. Who answered "Cancel"?

The "Delete" button shows confirm("Delete the account?"). The test presses it and waits for the "Account deleted" message, which never appears. In the video there is no dialog at all: it showed up and vanished in milliseconds. There is no bug in the app code, and the account was not deleted because confirm returned false. Playwright answered: when nobody listens to a dialog, it closes it itself. This article is about that default, the "a listener exists, so you must close the dialog" trap, and why most "dialogs" in modern apps are not dialogs at all.

How it works and why. Native browser dialogs (alert, confirm, prompt and beforeunload) block JavaScript on the page until the user answers. Automation cannot leave a page hanging without an answer, so Playwright set a rule: if nobody is subscribed to the dialog event, the dialog is automatically dismissed. For alert this is harmless, while confirm returns false and prompt returns null. If a listener exists, responsibility moves to the test: Playwright closes nothing any more, and the listener must call accept or dismiss, otherwise the page hangs and the action that caused the dialog does not finish before the timeout.

What happens to a dialog

a dialog appears no dialoglistener a listener existson / once auto-dismiss:confirm → falseprompt → null the test mustaccept() ordismiss(), or thepage hangs
Figure 1. Two modes: without a listener Playwright answers (with a refusal), with a listener only the test answers.

Example: deletion "without confirmation". A test that does not know about the dialog:

// before: no dialog listener
await page.getByRole('button', { name: 'Delete' }).click();
await expect(page.getByText('Account deleted')).toBeVisible(); // timeout

The failure looks like a waiting problem, but the cause is upstream: confirm returned false, the app deleted nothing, so "Account deleted" will never appear. Raising the timeout is pointless. The fix: subscribe before the click, capture the text and answer.

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 account?');
await expect(page.getByText('Account deleted')).toBeVisible();

The assertions about the dialog text are deliberately kept outside the handler: if an expect inside the handler fails, the error escapes the callback as an unhandled promise rejection: the test fails, but the dialog stays unanswered and the failure points at the callback, not at a test step. So the handler only collects data and answers, and the test checks after the click. The Dialog object has type() (alert, confirm, prompt, beforeunload), message(), defaultValue() for a prompt, and accept(text?) and dismiss().

The "a listener exists, so you must close the dialog" trap. As soon as at least one dialog listener exists, the automatic dismissal is turned off. If the handler forgets accept or dismiss (for example in one branch of an if), the page hangs. Global listeners in a fixture or beforeEach are just as dangerous: "accept everything automatically" hides messages the test should have checked. For a one-off dialog prefer page.once: the handler removes itself and does not touch other steps. For a sequence of dialogs in one scenario, page.on with a branch on type() fits.

const seen: { type: string; message: string; defaultValue: string }[] = [];
page.on('dialog', async (dialog) => {
  seen.push({
    type: dialog.type(),
    message: dialog.message(),
    defaultValue: dialog.defaultValue(),
  });
  if (dialog.type() === 'prompt') await dialog.accept('Duplicate account');
  else await dialog.dismiss(); // confirm returns false
});

await page.getByRole('button', { name: 'Rename' }).click(); // prompt
await expect(page.getByRole('heading', { name: 'Duplicate account' })).toBeVisible();

await page.getByRole('button', { name: 'Delete' }).click(); // confirm, answer: cancel
await expect(page.getByRole('heading', { name: 'Duplicate account' })).toBeVisible();
expect(seen.map((d) => d.type)).toEqual(['prompt', 'confirm']);

The dismiss() method checks the "negative" path: the user pressed "Cancel", and the data must stay. It is as important as the confirmation: a common mistake is to check only the success branch.

beforeunload. The "Leave the page?" dialog appears when the page has unsaved changes. In a test it is triggered, for example, with page.close({ runBeforeUnload: true }) and handled by the same listener. runBeforeUnload does not guarantee the page closes until the dialog is handled.

page.once('dialog', async (dialog) => {
  if (dialog.type() === 'beforeunload') await dialog.accept(); // leave anyway
  else await dialog.dismiss();
});
await page.close({ runBeforeUnload: true });

A native dialog or an HTML modal

Typical

page.on('dialog')

Catches only native browser dialogs. For an HTML modal the event never comes, so the listener does nothing and the test waits in vain.

Better

getByRole('dialog', { name })

A modal is ordinary page elements. Ordinary locators and web-first assertions work, with no listeners at all.

Figure 2. Before writing a listener, find out what you have: a native dialog or an element in the DOM.

Most "dialogs" in modern apps are HTML modals, not browser dialogs. They have no events: they are ordinary elements, best found through getByRole('dialog') with a name. A simple test: if you can inspect the dialog in DevTools and it carries the app's styling, it is HTML.

// an HTML modal is not a browser dialog: ordinary locators
const modal = page.getByRole('dialog', { name: 'Delete the account?' });
await expect(modal).toBeVisible();
await modal.getByRole('button', { name: 'Delete' }).click();
await expect(modal).toBeHidden();

Limits and alternatives. Native dialogs are rare today: apps move to HTML modals because those can be styled and tested. In Selenium dialogs are handled by driver.switchTo().alert(), and if a dialog is left unhandled, the next command fails with an "unexpected alert open" error. In Cypress dialogs are accepted automatically by default (alert and confirm return true), and cancelling has to be done explicitly through an event. In Playwright it is the opposite: the default is a refusal. So the Cypress habit ("it will be accepted anyway") is the cause of the mistake in the example above.

Common mistakes.

  • Pressing a "Delete" button with a confirm and no listener: the dialog is dismissed automatically and the deletion does not happen.
  • Subscribing after the click: the dialog was already dismissed automatically, or the test hung.
  • No accept/dismiss in one branch of the handler: the page hangs.
  • page.on instead of page.once in beforeEach: the handler becomes global for the whole file and hides other dialogs.
  • Looking for an HTML modal with page.on('dialog'): the event never comes, because it is not a native dialog.

Check yourself

A test presses "Delete" with a confirm and waits for "Account deleted", which does not appear. The test has no dialog listener. What happened, and why will a longer timeout not help?

Answer

With no listener Playwright dismissed the dialog automatically, so confirm returned false and the app did not delete anything. The expected message will never appear, so a longer timeout changes nothing. You need page.once('dialog', d => d.accept()) before the click.

A page.on('dialog') handler contains only if (dialog.type() === 'prompt') await dialog.accept('x'). What happens when a confirm appears?

Answer

A listener exists, so there is no automatic dismissal, and in the confirm branch nobody calls accept or dismiss. The page hangs and the action that started the dialog does not finish before the timeout. Every branch must answer (add else await dialog.dismiss()).

A test for the "Delete the account?" modal adds page.on('dialog', …), but the handler is never called, while the modal is visible on screen. Why?

Answer

It is an HTML modal, not a native browser dialog, so there is no dialog event. Ordinary locators work: page.getByRole('dialog', { name: … }) and the toBeVisible and toBeHidden assertions.

In an interview. Junior: Playwright dismisses native dialogs by default, so for a confirm I register page.once('dialog') beforehand and call accept. Middle/Senior: If a listener exists, the dialog must be closed in every branch, otherwise the page hangs. I check the dialog text outside the handler so a failed assertion does not get lost in a callback. I do not set a global "accept all": it hides what the test should check. I test custom modals as ordinary elements through getByRole('dialog'), because they are not browser dialogs.