I have automation scenario that sometimes the system return javascript alert and sometimes not at all. I don't know what the cause of this, probably the network issue. I already create the alert handler for this:
public boolean isAlertPresent() {
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.alertIsPresent());
return true;
}
I call this in one of my step that sometimes appear alert:
public WSSPage enterAndSearchContent(String title) throws InterruptedException {
waitForElementTextWithEnter(searchTextField, title);
while (isAlertPresent()){
Alert alert = driver.switchTo().alert();
alert.dismiss();
break;
}
return PageFactory.initElements(driver, WSSPage.class);
}
The problem is when the alert doesn't show up, it will give me NoAlertPresentException, and the automation result will be failed. I want the code to move on if the alert doesn't happen by moving to the next line, in this case it will just return PageFactory.initElements(driver, WSSPage.class);
Can you help me provide a better code from this?
Thanks a lot.
JavascriptExecutor worked for you. Just take care that you should execute it before clicking the event which invoke alert.
((JavascriptExecutor) driver).executeScript("window.confirm = function(msg) { return true; }");
Note :- do not use it after clicking on event which invoke alert confirmation box. Above code by default set the confirmation box as true means you are accepting/click on ok on all confirmation box on that page if invoked
Hope it will help you :)
You can modify the method isAlertPresent as given below and try it. It may help you.
public boolean isAlertPresent() {
try{
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.alertIsPresent());
return true;
}
catch (NoAlertPresentException noAlert) {
return false;
}
catch (TimeoutException timeOutEx){
return false;
}
}
You can include that particular exception in try catch. Then the exception will be catched and will not through any error and your execution will continue.
Also create a implicit wait to handle this with less timestamp.
Related
I need to wait for a specific loader to complete loading once the button has been pressed, please take a look at the following image below:
As you can see from the image above, once the button has been pressed the ajax loader appears inside the button.
I have created the following selector to locate the button:
//form[contains(#id, 'messageform')]//button/span
Currently accepting the request (Clicking on the button) fails my test case as the script continues to the next test steps without waiting for the loader to complete.
I have tried the following and more, with no luck:
Injecting JS to wait for the page to fully load.
ExpectedCondition<Boolean> expectation = driver -> ((JavascriptExecutor) driver).executeScript("return document.readyState").toString().equals("complete");
ExpectedConditions.invisibilityOf(element)
WebDriver driver = getDriver();
WebDriverWait exists = new WebDriverWait(driver, timer);
exists.until(ExpectedConditions.refreshed(
ExpectedConditions.invisibilityOf(element)));
Any ideas?
You should use .stalenessOf() to wait until an element is no longer attached to the DOM.
Something like this (tweak to your case):
WebElement somePageElement = driver.findElement(By.id("someId"));
WebDriverWait wait = new WebDriverWait(webDriver, 10);
// do something that changes state of somePageElement
wait.until(ExpectedConditions.stalenessOf(somePageElement));
And the good thing is you don't have to handle any exceptions.
Alternatively, you can also create a method and handle exceptions like so:
public static void WaitForCommission (WebDriver driver) throws Exception {
for (int second = 0; second++) {
if (second >= 30) fail("timeout");
try {
if (IsElementActive(By.id("someElementID"), driver))
break;
} catch (Exception e) {}
Thread.sleep(1000);
}
}
private static boolean IsElementActive(By id, WebDriver driver) {
WebElement we = driver.findElement(id);
if(we.isEnabled())
return true;
return false;
}
I am working on cloudbase project which is having user authentication module. User can be authenticated to system using user credentials and also with using OAuth authentication.
I am automating this with Selenium but when I am trying to click on 'sign-in' button it does not work,
#BeforeTest
public void setUp()
{
driver = new FirefoxDriver();
driver.get("Application URL");
driver.manage().window().maximize();
}
#Test
public void enterCredentials()
{
driver.findElement(By.id("cred_userid_inputtext")).sendKeys("email address");
driver.findElement(By.id("cred_password_inputtext")).sendKeys("password");
driver.findElement(By.id("cred_sign_in_button")).click();
}
I have tried same using sendKeys(Keys.ENTER) and with sendKeys(Keys.RETURN)
Also tried using Actions
{
WebElement signIn_button = driver.findElement(By.id("cred_sign_in_button"))
Actions enterSignIn = new Actions(driver);
enterSignIn.moveToElement(signIn_button);
enterSignIn.click();
enterSignIn.perform();
}
For some reason, on some pages Firefox seems to require special treatment for Click(). I solved it this way (in C#, but Java should be similar):
// special workaround for the FirefoxDriver
var actions = new Actions(driver);
actions.MoveToElement(element);
ToolBox.DisableTimeout(testParams);
actions.Release().Build().TryPerform();
ToolBox.EnableTimeout(testParams);
actions.MoveToElement(element);
actions.Click().Build().Perform();
Explanation: I explicitly call Release() before calling Click(). Sometimes it's necessary, sometimes it isn't. If it is not necessary, then calling Release() ends up in waiting until the implicit timeout (if you have any) is over and then raising an exception. That is why I temporarily disable the timeout when calling Release() and also why I wrap it in a TryPerform() method, in order to ignore the exception. A look inside my TryPerform() method:
public static bool TryPerform(this IAction action)
{
try
{
action.Perform();
}
catch (Exception)
{
return false;
}
return true;
}
I know, there are no extension methods in Java, but you can probably solve this similarly.
Some times sleep before click will simulate click correctly. like
Thread.sleep(3000);
driver.findElement(By.id("cred_sign_in_button")).click();
If above one does not works, as you already tried with all locators and Actions, so try with java script executor
WebElement element = driver.findElement(By.id("cred_sign_in_button"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);
Thank You,
Murali
Try this,
WebElement element = driver.findElement(By.id("cred_sign_in_button"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
[enter link description here][1]executor.executeScript("arguments[0].click();", element);
Visit Here
You can try explicit wait with expected conditions
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable(By.id("cred_sign_in_button"))).click();
I know there are several threads regarding this topic, but I am not necessarily looking for a solution, but rather an explanation. I work on a very large automation suite that tests a web application via mobile phones using browserstack. My stability is very low.. and it is due to this error getting thrown at me! Occasionally it will work and occasionally it will not.. I can not use Actions because Browserstack does not support that.. WHY does this error exist and has anyone had any success it working around it. I always wait for an object using wait.until(ExpectedConditions), but sometimes this does not work well enough. I cant quite catch it as an exception since it is an Unknown error. Also, our standards do not allow for a Thread.sleep(). Any ideas? Thank you so much
And here is a screen of some code..
You are waiting for a WebElement to be clickable, then again you are finding a list of WebElements and clicking the first element.
This does not guarantee that you are clicking the element you waited for it be clickable.
public void waitAndClickElement(WebElement element) {
driverWait.until(ExpectedConditions.elementToBeClickable(element)).click();
}
In your case,
public void clickImageView() {
driverWait.until(ExpectedConditions.elementToBeClickable(listImageView)).click() ;
}
Element is normally not click able due to following reasons .
Html is loading and client is still receiving updates from server
When Scrolling
It can be due to some object is overlapping target
problem 3 can not be resolved you need to fix your code in this wait i wait for HTML to ready and then verify is it click able or not this has eliminated such exceptions from my code
how ever i made a solution for problem 1 and 2 you can simply use my custom wait before clicking . call this function
public static void waitForElementPresent(final By by, int timeout,WebDriver driver)
After this if you are using browser other then chrome then call Scroll to that object this would fix you problem
Code
public static void waitForElementPresent(final By by, int timeout,WebDriver driver) {
waitForPageLoad(driver);
WebDriverWait wait = (WebDriverWait)new WebDriverWait(driver,40).ignoring(StaleElementReferenceException.class);
/* wait.until(new ExpectedCondition<Boolean>(){
#Override
public Boolean apply(WebDriver webDriver) {
WebElement element = webDriver.findElement(by);
return element != null && element.isDisplayed();
}
}); */
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
wait.until(ExpectedConditions.presenceOfElementLocated(by));
wait.until(ExpectedConditions.elementToBeClickable(by));
WebDriverWait wait2 = new WebDriverWait(driver, 40);
wait2.until(ExpectedConditions.elementToBeClickable(by));
}
//wait for page to laod
public static void waitForPageLoad(WebDriver driver) {
ExpectedCondition<Boolean> pageLoadCondition = new
ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete");
}
};
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(pageLoadCondition);
}
This is due to the speed at which selenium runs. It will try and find elements before the page has loaded, thus resulting in this error.
For the code sample you provided, the .until() returns the WebElement you are waiting for. You can use the code below to click it rather than scraping the page again.
public void clickImageView()
{
driverWait.until(ExpectedConditions.elementToBeClickable(listImageView)).click();
}
I want to disable all alerts using webdriver while disabling alerts should affect as true.
Thanks
Akmal Rasool
According to me, you want to check for alerts and if any alert is present you want to accept those alerts.
See the below code for the same.
public boolean alertPresence()
{
boolean presence = false;
try
{
driver.switchTo().alert();
presence = true;
alert.accept();
}
catch (NoAlertPresentException Ex)
{
Ex.printStackTrace;
presence = false;
}
}
I am testing my form and when I don't type needed data I get javascript alert in my web app that tells the user to enter missing data. I can't handle this with selenium because when I partially fill form and try to submit I get exception
org.openqa.selenium.UnhandledAlertException: Modal dialog present
If I catch exception the alert in webdriver is not shown. Is that any solution to solve this issue?I would like to be able to submit form and catch the alert. I am using Linux Mint,Firefox 18 and selenium 2.28.0 with java
Best regards
UPDATE
I have following in my code
somePage.fillName(sth); //only 1 of 2 required field are filled
somgePage.submit(); //here js alert is shown right after clicking submit
somePage.getCurrentAlert();
//here are code parts
public Alert getCurrentAlert(){
return driver.switchTo().alert();
}
public AdminHome submit(){
saveUrl();
WebElement submit = driver.findElement(By.id("add_quiz_submit_button"));
try{
submit.click();
if(urlChanged()){
return new AdminHome(driver);
}
}
catch(Exception e){
e.printStackTrace();// exception 1
return null;
}
return null;
}
//Exception 1
org.openqa.selenium.UnhandledAlertException: Modal dialog present
//The test fails because of:
org.openqa.selenium.NoAlertPresentException: No alert is present (WARNING: The server did not provide any stacktrace information)
However if I click manual on submit the test work as expected. Thanks in advance
you should handle the alert as soon as the action is done and there shouldn't be any other action before handling the alert.
for instance your code should be
try{
submit.click();
if (alertPresent())
getCurrentAlert();
if(urlChanged()){
return new AdminHome(driver);
}
}
This will check alert and then accept the alert. The interaction of webdriver is more similar to the action we interact with manually with browser. So when the click on submit is done we will be able to see alert and no actions can be done until accept or reject it.
Vishal
It is because driver accepts the alert itself when the UnhandledAlertException is thrown. How can you submit the form if you have filled it partially?
If it is even possible, just catch that exception, and in catch block write the line which clicks on the submit button.
Use Robot class (Press enter) to close modal dialog box
try {
(new Robot()).keyPress(java.awt.event.KeyEvent.VK_ENTER);
(new Robot()).keyRelease(java.awt.event.KeyEvent.VK_ENTER);
} catch (AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}