Handle Javascript Alert using Selenium WebDriver
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
package simpletests; import org.junit.Assert; import org.openqa.selenium.Alert; 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.Test; public class JSAlert { WebDriver driver; @Test public void alertWindow() throws Exception { System.setProperty("webdriver.chrome.driver", "D:\\AUTOQA\\chromedriver_win32\\chromedriver.exe"); driver = new ChromeDriver(); driver.get("http://demosite.qualitylearning.in/wp/java-script-alert/"); driver.manage().window().maximize(); Thread.sleep(3000); driver.findElement(By.xpath("//*[@type='button']")).click(); Thread.sleep(3000); try { WebDriverWait wait = new WebDriverWait(driver, 2); wait.until(ExpectedConditions.alertIsPresent()); Alert alert = driver.switchTo().alert(); System.out.println(alert.getText()); alert.accept(); Assert.assertTrue(alert.getText().contains("Hello I am JavaScript Alert!")); } catch (Exception e) { //exception handling } driver.close(); } } |
Result:
1 2 3 4 5 6 7 8 9 10 11 |
Starting ChromeDriver 2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f) on port 7729 Only local connections are allowed. Dec 12, 2017 6:26:12 PM org.openqa.selenium.remote.ProtocolHandshake createSession INFO: Detected dialect: OSS Hello I am JavaScript Alert! PASSED: alertWindow =============================================== Default test Tests run: 1, Failures: 0, Skips: 0 =============================================== |
Appreciation for really being thoughtful and also for deciding on certain marvelous guides most people really want to be aware of.