WebDriver how to wait for alert in selenium 2

As we have seen in my previous posts, we can use textToBePresentInElementLocated(By, String) WebDriver condition to wait for text present on page and we can use elementToBeClickable(By locator) to wait for element clickable/present on page. If you read both those posts, We had used explicit waits in both the cases and both are canned expected conditions of webdriver so we can use them directly in our test case without any modifications.

Sometimes you will face wait for alert scenario where you have to wait for alert before performing any action on your software application web page. If you know, we can use "waitForAlert" command in selenium IDE to handle alerts. In WebDriver/Selenium 2, You can use WebDriver's built in canned condition alertIsPresent() with wait command as bellow.

WebDriverWait wait = new WebDriverWait(driver, 15);

Look in to above syntax. 1st syntax described how much time it has to wait and 2nd syntax describes the waiting condition. Here we have used alertIsPresent() condition so it will wait for the alert on page. Let me give you full practical example to describe scenario perfectly.

Copy paste bellow given test case in your eclipse with JUnit and then run it. You can View how to configure eclipse with JUnit if you have no idea.

package junitreportpackage;

import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Mytest1 {
 WebDriver driver = null;
 public void beforetest() {
  System.setProperty("webdriver.gecko.driver", "D:\\Selenium Files\\geckodriver.exe");
  driver = new FirefoxDriver();
 public void aftertest() {
 public void test () 
  driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("My Name");
  WebDriverWait wait = new WebDriverWait(driver, 15);
  String alrt = driver.switchTo().alert().getText();

Above example will wait for the alert on page and as soon as alert appears on page, it will store alert text in variable 'alrt' and then will print to it in console.

No comments:

Post a comment