Selenium can handle java script alerts in a very effective manner but it
can not handle modal alert box which gets created by OS itself e.g.: java
script error message alert. Now how do you handle these java script alerts,
what can you do with those alerts, lets see one by one with the code.
Scenario as an example -:
Select a object from the page, Click on Delete button. It triggers a alert saying "Object is going to be deleted from the database, Click OK to Confirm or Cancel to Cancel the Operation".
We need to test the message of the Alert, Clicking Ok and Clicking Cancel also.
Steps to be Performed
Select the Object to delete from the page.
Click on Delete button, it triggers the Alert message.
Select a object from the page, Click on Delete button. It triggers a alert saying "Object is going to be deleted from the database, Click OK to Confirm or Cancel to Cancel the Operation".
We need to test the message of the Alert, Clicking Ok and Clicking Cancel also.
Steps to be Performed
Select the Object to delete from the page.
Click on Delete button, it triggers the Alert message.
Sample code:
/* Code to switch the control to Alert message*/
Alert testAlrt=driver.switchTo().alert();
testAlrt is the Controlling object of the Alert. Now you can use this object to Accept/get Text/Dismiss the alert.
/* To get the text from the alert */
String sAltText=testAlrt.getText();
/* To Accept any alert, it means Clicking OK button */
testAlrt.accept();
/* To dismiss any alert, It means Clicking Cancel button */
testAlrt.dismiss();
/* If the Alerts gets created using Ajax call, then you may need to wait till the Alert present */
WebDriverWait wdWait= new WebDriverWait(driver, 10);
wdWait.until(ExpectedConditions.alertIsPresent());
/* Code to switch the control to Alert message*/
Alert testAlrt=driver.switchTo().alert();
testAlrt is the Controlling object of the Alert. Now you can use this object to Accept/get Text/Dismiss the alert.
/* To get the text from the alert */
String sAltText=testAlrt.getText();
/* To Accept any alert, it means Clicking OK button */
testAlrt.accept();
/* To dismiss any alert, It means Clicking Cancel button */
testAlrt.dismiss();
/* If the Alerts gets created using Ajax call, then you may need to wait till the Alert present */
WebDriverWait wdWait= new WebDriverWait(driver, 10);
wdWait.until(ExpectedConditions.alertIsPresent());
0 Comments