Wednesday, January 8, 2014

Handling JavaScript Alert in WebDriver

Handling JavaScript Alert is big question if you have just started learning WebDriver. Because we always get multiple pop-ups some time we get information about validity of input and some time these pop-up speaks about error, and also about response.
But as a tester we need to verify the alert message and for the same we need to handle the Alert pop up. So its time to celebrate because WebDriver have provided us with Alertclass to deal with JavaScript Alert.

Since I have created this alert through a basic html file and  it has one button Ok. Butthere is another kind of alert known as Confirm Box Alert and it normally have two button
1-Ok button
2- Cancel button
Since both alert is handled in the same way so here I am taking the Confirm Box Alert here
Scenario : Suppose we have one button, and once we hit on the button a alert appears with two button Ok and Cancel
a) In first case if end user click on Ok button
@Test
public void testAlertOk()
{
//Now we would click on AlertButton
WebElement button = driver.findElement(By.id("AlerButton"));
button.click();
try {
//Now once we hit AlertButton we get the alert
Alert alert = driver.switchTo().alert();
//Text displayed on Alert using getText() method of Alert class
String AlertText = alert.getText();
//accept() method of Alert Class is used for ok button
alert.accept();
//Verify Alert displayed correct message to user
assertEquals("this is alert box",AlertText);
} catch (Exception e) {
e.printStackTrace();
}
}
b) In second case we want to click on Cancel button
So above code would remain same only thing that would change in above script is
alert.accept();
For clicking on Cancel we need to use dismiss() method of Alert Class


alert.dismiss();

Hope this script would help you to handle Alert in WebDriver

No comments:

Post a Comment