PopUps
Web Applications generate 3 different types of PopUps; namely,
1| JavaScript PopUps
2| Browser PopUps
3| Native OS PopUps [e.g., Windows Popup like Upload/Download]
JavaScript pop-ups are generated by the web application code. Selenium provides an API to handle JavaScript pop-ups
Alert alert = driver.switchTo().alert();
accept(), dismiss(), getText(), and sendKeys() are some of the most important Alert functions.
import org.openqa.selenium.Alert;
Alert alert = driver.switchTo().alert();
System.out.println(closeAlertAndGetItsText());
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
System.out.println(alertText); //Print Alert popup
if (acceptNextAlert) {
alert.accept(); //Accepts Alert popup [OK]
} else {
alert.dismiss(); //Cancel Alert popup
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
Alert alert = driver.switchTo().alert();
assertEquals("Expected Value", closeAlertAndGetItsText());
driver.findElement(By.id(Value)).click();
isAlertPresent();
private void isAlertPresent() {
try {
Alert alert = driver.switchTo().alert();
System.out.println(alert.getText());
alert.accept();
} catch (NoAlertPresentException e) {
System.out.println("Alert not available");
return;
}
}
Web Applications generate 3 different types of PopUps; namely,
1| JavaScript PopUps
2| Browser PopUps
3| Native OS PopUps [e.g., Windows Popup like Upload/Download]
JavaScript pop-ups are generated by the web application code. Selenium provides an API to handle JavaScript pop-ups
Alert alert = driver.switchTo().alert();
accept(), dismiss(), getText(), and sendKeys() are some of the most important Alert functions.
Handling JS PopUp
#Print Alert Text and Close
import org.openqa.selenium.Alert;
Alert alert = driver.switchTo().alert();
System.out.println(closeAlertAndGetItsText());
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
System.out.println(alertText); //Print Alert popup
if (acceptNextAlert) {
alert.accept(); //Accepts Alert popup [OK]
} else {
alert.dismiss(); //Cancel Alert popup
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
#Assert Alert Text
Alert alert = driver.switchTo().alert();
assertEquals("Expected Value", closeAlertAndGetItsText());
isAlertPresent()
driver.findElement(By.id(Value)).click();
isAlertPresent();
private void isAlertPresent() {
try {
Alert alert = driver.switchTo().alert();
System.out.println(alert.getText());
alert.accept();
} catch (NoAlertPresentException e) {
System.out.println("Alert not available");
return;
}
}
No comments:
Post a Comment