org.openqa.selenium.NoAlertPresentException: no alert open org.openqa.selenium.NoAlertPresentException: no alert open selenium selenium

org.openqa.selenium.NoAlertPresentException: no alert open


The code has to wait for alert. Below is the sample code

try {    WebDriverWait wait = new WebDriverWait(driver, 2);    wait.until(ExpectedConditions.alertIsPresent());    Alert alert = driver.switchTo().alert();    System.out.println(alert.getText());    alert.accept();    Assert.assertTrue(alert.getText().contains("Thanks."));} catch (Exception e) {    //exception handling}


This is a very bad approach to use try-catch especially in selenium based test cases and their use should be limited:

Let's understand the real solution of this problem and why the given solution is incorrect because:

  1. If we try to call alert.getText() after alert.accept(); it would obvious that it going to throw error because we have already closed the alert.

  2. It is working fine because by using try-catch, it will going to handle the exception.

  3. The problem is that assertion is never checked here.

Code: The below code will terminate every time even before checking the assertion.

alert.accept();    Assert.assertTrue(alert.getText().contains("Thanks."));

Corrected Code: The alert.accept(); should be call after getting the text.

    WebDriverWait wait = new WebDriverWait(driver, 2);    wait.until(ExpectedConditions.alertIsPresent());    Alert alert = driver.switchTo().alert();    Assert.assertTrue(alert.getText().contains("Thanks."));    alert.accept();