This is happening because of the default behaviour of the driver when it encounters an alert. The default behaviour was set to "ACCEPT", thus the alert was closed automatically, and the switchTo().alert() couldn't find it explicitly.
The solution is to modify the default behaviour of the driver to ("IGNORE"), so that it doesn't close the alert but just ignores it:
DesiredCapabilities dc = new DesiredCapabilities();
dc.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.IGNORE);
d = new FirefoxDriver(dc);
Then you can handle it easily and use the try-catch exception handling code to catch an error if any:
try {
click(myButton);
} catch (UnhandledAlertException f) {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
System.out.println("Alert data: " + alertText);
alert.accept();
} catch (NoAlertPresentException e) {
e.printStackTrace();
}
}
If you are interested to learn Selenium on a much deeper level and want to become a professional in the testing domain, check out Intellipaat’s automation testing course!