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. selenium wait until alert is present is useful to pause test execution until alert dispalyed on page.

Sometimes you will face selenium wait for alert scenario where selenium wait until alert is present before performing any action on your software application web page. wait for alert selenium will wait unitl elert display on 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 for wait until alert is present selenium.

WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.alertIsPresent());

Look in to above syntax. 1st syntax described how much time it has to wait for alert selenium and 2nd syntax describes the waiting condition. Here we have used alertIsPresent() condition so it will wait for alert selenium 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.

Wait for alert selenium example

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;
 
 @Before
 public void beforetest() {
  System.setProperty("webdriver.gecko.driver", "D:\\Selenium Files\\geckodriver.exe");
  driver = new FirefoxDriver();
  driver.manage().window().maximize();
  driver.get("http://only-testing-blog.blogspot.com/2014/01/new-testing.html");
 }
 
 @After
 public void aftertest() {
  driver.quit();
  
 }
 
 @Test
 public void test () 
  {  
  driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("My Name");
  WebDriverWait wait = new WebDriverWait(driver, 15);
  wait.until(ExpectedConditions.alertIsPresent());
  String alrt = driver.switchTo().alert().getText();
  System.out.print(alrt);
  }
 
 
 
 }

In above example selenium wait until alert is present 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