How to automate Alert boxes and Pop-ups


#1

Handling alerts

Surely you have encountered a situation when a pop-up jumps out of nowhere and needs to be confirmed or dismissed. Those pop-ups will cause your test to fail if not handled correctly. There is a simple way to handle such situations using driver.switchTo().alert method.

The alert interface provides the below few methods which are widely used in Selenium Webdriver.

  • dismiss() - Click on the ‘Cancel’ button of the alert.
  • accept() - Click on the ‘OK’ button of the alert.
  • getText() - Capture the alert message.
  • sendKeys(String stringToSend) - Send some data to alert box.

In this example, we will use this neat web page to automate a pop-up confirm scenario.

The steps are the following:

  • Locate the button that triggers the pop-up, generate the selector and use .click() method on it.
Java Projects:
this.wait.until(ExpectedConditions.visibilityOfElementLocated(this.makePopUpButton)).click(); 
TypeScript Projects:
await browser.wait(ExpectedConditions.visibilityOf(element(this.makePopUpButton)), browser.allScriptsTimeout, this.makePopUpButton.toString());
await element(this.makePopUpButton).click(); 
  • After that accept the pop-up using the .switchTo().alert().accept() method
Java Projects:
driver.switchTo().alert().accept();
TypeScript Projects:
browser.switchTo().alert().accept();

The complete Java project code for this step in the Page Object file would look like this:

public PopupPo AcceptPopup() {
        // Click on the button to make a popup
        this.wait.until(ExpectedConditions.visibilityOfElementLocated(this.makePopUpButton)).click();

        // Accept the poput
        driver.switchTo().alert().accept();
        
        return this;
}

That’s about it! Use your method in the actual test and get rid of those alerts!

@Test
public void AcceptThePopup() {
        WebDriver driver = getDriver();

        // Instantiate PO file
        PopupPo popupTest = new PopupPo(driver);
        popupTest.open("https://the-internet.herokuapp.com/javascript_alerts");

        // Click the button and accept the popup
        popupTest.AcceptPopup();
}

Of course, you can use the alert.dismiss() or alert.sendKeys() methods in the same fashion.


Find out more about handling alerts in TypeScript Protractor Projects and here for Java Projects.