lecture 13 of 200 completed

Browser dialogs: alert, confirm and prompt

A native dialog is not part of the page. Your selectors cannot see it, and an unhandled one blocks everything after it.

Your test clicks Delete. A confirmation box appears asking "Are you sure?". Your next line looks for the updated table and fails with a message about the element not being found, or about an unexpected alert being open.

The dialog is not part of the page. It is drawn by the browser, outside the DOM. No CSS selector can reach it, and while it is open the page underneath is frozen.

Three kinds exist, and they behave differently:

alert shows a message with one OK button.

confirm asks a question with OK and Cancel. Your choice changes what the app does, so both paths are worth testing.

prompt asks for text input, with OK and Cancel.

Selenium handles all three through switchTo().alert():

await driver.findElement(By.css('[data-testid="delete"]')).click();

const alert = await driver.switchTo().alert();

const message = await alert.getText();
expect(message).to.equal('Delete this contact? This cannot be undone.');

await alert.accept();     // press OK

accept() is OK. dismiss() is Cancel. For a prompt, sendKeys('text') types into it before you accept.

Three things worth getting right.

Read the text before you accept it. The dialog is a promise your app makes to the user, and a wrong or alarming message is a real bug. Once you accept, the text is gone.

Test the Cancel path too. Click delete, dismiss, and assert the row is still there. In my experience this is where the bug actually lives: the app deletes optimistically before the user confirms, and only the cancel test catches it.

Wait for the dialog. It may take a moment to appear:

await driver.wait(until.alertIsPresent(), 5000);
const alert = await driver.switchTo().alert();

⚠️ An unhandled dialog breaks everything after it.

While a native dialog is open, the browser will not let you do anything else. Every subsequent command fails with UnexpectedAlertOpenException, and the messages point at whatever you tried next rather than at the dialog. It reads like a dozen unrelated failures.

If a whole run collapses after one point, check whether something opened a dialog nobody closed.

One last note that saves time on modern apps. Most "are you sure?" boxes today are not native dialogs. They are HTML built by the app, styled to look like part of the product. Those you handle with ordinary selectors and clicks. Check the Elements tab first: if you can see the dialog in the DOM, it is HTML, and switchTo().alert() will fail with "no such alert".

Remember this: native dialogs live outside the DOM, read the text before accepting, and always test Cancel.

Reference: JavaScript alerts and prompts.