34. WebDriver Explicit Wait :How to wait for alert in webdriver

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

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 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.

package Others;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class webdriver_explicit {
                       
            @BeforeClass
            public void beforeClass() {
                        System.setProperty("webdriver.chrome.driver", "D:\\Softwares\\chromedriver_win32\\chromedriver.exe");   
                        driver = new ChromeDriver();
                        driver.manage().window().maximize();
                        driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");                       
            }           
            public WebDriver driver;
            @Test
            public void testIsDiplayed_Enabled() throws Exception {
                       
                        driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("alpesh");
                        WebDriverWait wait = new WebDriverWait(driver, 15);
                        driver.findElement(By.xpath("//input[@value='Show Me Alert']")).click();
                        wait.until(ExpectedConditions.alertIsPresent());
                        String alrt = driver.switchTo().alert().getText();
                        System.out.print(alrt);           
            }
            @AfterClass
            public void afterClass() throws Exception {
                        driver.quit();
            }
}

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.

Note: You can learn how to handle alerts in later post(Alert Link)

No comments:

Post a Comment