Testing a javascript popup with selenium

Testing a javascript popup with selenium

To test a JavaScript popup with Selenium, you can use the .alert property of the WebDriver object to access the alert and then use the .accept() or .dismiss() methods to interact with it.

Here is an example of how you can do this:// Import the Alert and WebDriverWait classes from the Selenium package
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class PopupTest {
public static void main(String[] args) {
// Set the path to the chrome driver
System.setProperty(“webdriver.chrome.driver”, “/path/to/chromedriver”);

// Create a new ChromeDriver
WebDriver driver = new ChromeDriver();

// Navigate to the page with the JavaScript popup
driver.get(“http://ChangeUrlHere.com/popup.html”);

// Click the button to trigger the popup
driver.findElement(By.id(“somebutton”)).click();

// Then, you can use the WebDriverWait class to wait for the alert to appear
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.alertIsPresent());

// Switch the focus of the web driver to the JavaScript popup
Alert alert = driver.switchTo().alert();

// Get the text of the popup
String popupText = alert.getText();
System.out.println(“Printing the Popup text: ” + popupText);

// Accept the popup
alert.accept();

// To dismiss the alert (i.e., click the “Cancel” button), you can call the dismiss() method
alert.dismiss();
}

You can also use the .dismiss() method to dismiss the alert or the .sendKeys(String) method to enter text into a prompt dialogue.

It’s a good idea to wrap the code that interacts with the alert in a try-catch block in case the alert is not present, or the interaction with it fails for some reason.try {
// Wait for the alert to appear
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.alertIsPresent());

// Get the alert and accept it
Alert alert = driver.switchTo().alert();
alert.accept();
} catch (NoAlertPresentException e) {
// Alert not present
System.out.println(“Alert was not present”);
} catch (WebDriverException e) {
// Interaction with the alert failed
System.out.println(“Failed to interact with the alert: ” + e.getMessage());
}

You can also use the sendKeys() method to enter text into a prompt dialog.// To enter text into a prompt dialog, you can use the sendKeys() method
alert.sendKeys(“Text to enter”);

// Then, you can accept the alert as usual
alert.accept();

It’s a good practice to add assertions to your automated test to validate that the popup is displayed and has the expected text.

You can also add test cases to verify that the popup is dismissed or accepted as expected.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *