Selenium Show A Custom Message Instead Of "TimeOut" - selenium

I'm writing a test code with Selenium. I'm waiting for an element like this:
WebDriverWait webDriverWait = new WebDriverWait(driver, 60);
webDriverWait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("Link Text")));
I need to show a custom message instead of time out message if expected element doesn't come.
I used withMessage() method bu is not working in this situation.
webDriverWait.withMessage("message");
How can I show a custom message instead of a time out message.

You need to catch the timeOutException and at that point provide your own custom error message. Something like:
try {
WebDriverWait webDriverWait = new WebDriverWait(driver, 60);
webDriverWait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("Link Text")));
} catch(TimeOutException e) {
System.out.println("[DEBUG] Could not find element in allowed time...")
}

Related

How to applied a default wait time to visible or find or display of webElement in selenium except using Implicit wait or webdriver wait

I want to apply a one specification to my selenium test's code as webdriver have to wait for web element to display or load on a webpage for anytime. It should be applicable for a every web element in the code. Is there any way to get this. Instead of applying implict wait or Webdriver wait when ever it required. I can use this specification so that even though in future any webElement take sometimes to get visible it will wait default till it is visible.
You can create a method which receives By as parameter and returns WebElement, and use it for all the element search instead of driver.findElement()
// Java syntax
public WebElement findElement(By by) {
WebDriverWait wait = new WebDriverWait(driver, 30);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(by));
return element;
}
You can also put WebDriverWait wait = new WebDriverWait(driver, 30); at class level instead of creating a new instance every time.

Wait for element for certain amount of time

I have been experiencing one issue during test automation implementation. Particularly test checks if a hamburger menu is displayed.
So far I defined the element and subelement, and I need to really wait just one second, and not to waste time If I know that element will not be displayed after several seconds.
WebDriverWait wait = new WebDriverWait(getDriver(), 1);
WebElement hamMenu = el.findElement(By.xpath(HAMBURGER_MENU_GENERAL_XPATH));
How to implement the method findElement in the way it will try to find the element in one sec? I do not wish to stay longer... Thanks
Try this -
WebElement elem = new WebDriverWait(driver, 1).until(ExpectedConditions.visibilityOfElementLocated(By.xpath(HAMBURGER_MENU_GENERAL_XPATH)));
If I summarize your requirement is as follows :
Check if a hamburger menu is displayed only for 1 second : You need WebDriverWait with proper ExpectedConditions
Element may/not not be displayed after several seconds : You need to wrapup your code in a try-catch {} block to be able to proceed further in absence of the hamburger.
Youe effective code can be :
try {
WebElement hamburger = new WebDriverWait(getDriver(), 1).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("HAMBURGER_MENU_GENERAL_XPATH")));
System.out.println("Hamburger is displayed in 1 sec");
//rest of your code
} catch (NoSuchElementException e){
System.out.println("Hamburger wasn't displayed in 1 sec");
//rest of your code
}
I got it. Thanks for all hints. This will wait just only for short time which is intended.
public boolean isHamMenuDisplayed(){
getDriver().manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
if (el.findElements(By.xpath(HAMBURGER_MENU_GENERAL_XPATH)).size() == 0)
return false;
else
return true;}

PhantomJS and Selenium - Having issues while trying to use wait when searching for an element

I am trying to do some testing in a headless browser, to test filling in a form.
I am using code that I was shown from the following example :
github link to example of using phantomjs
My code :
WebDriverWait wait = new WebDriverWait(driver, 30);
driver.get("<URL HERE, left out for privacy on stack overflow!>");
By amount = By.id("amountField");
wait.until(ExpectedConditions.presenceOfElementLocated(amount));
Error in intelliJ :
until(java.util.function<? super org.openqa.selenium.WebDriver, V) in FluentWait cannot be applied to :
(org.openqa.selenium.support.ui.ExpectedCondition<org.openqa.selenium.WebElement>)
I am not really sure where I am going wrong here - but I have spent two hours trying to fix this issue.
element I am looking for on page :
<input name="amount0" id="amountField" value="" class="amount form-control" type="number" pattern="\d+(\.\d*)?" maxlength="10" placeholder="Amount">
Seems that the issue is not with PhantomJS. The error you see tells it all.
Your code seems to considering the WebDriverWait wait as a Fluent Wait where as you have exported import org.openqa.selenium.support.ui.ExpectedConditions; which is causing the error.
In the documentation as well, the author have used Explicit Wait importing import org.openqa.selenium.support.ui.ExpectedConditions; and import org.openqa.selenium.support.ui.WebDriverWait;
I would suggest you to try this approach:
Let the url get loaded first.
Define the Explicit Wait.
Define the ExpectedConditions in untill.
Get the status of the Element.
Sysout the Status.
If it fails, increase the duration of Explicit Wait to fulfill ExpectedConditions.
You can have a look at this modified code:
driver.get("<URL HERE, left out for privacy on stack overflow!>");
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("amountField")));
boolean status=element.isDisplayed();
if (status)
{
System.out.println("Element is displayed");
}
else
{
System.out.println("Element is not displayed");
}
Let me know if this helps you.

How to select a value from a drop down menu

I want to select the option from the drop-down menu. I tried a number of ways but I failed.
I tried:
WebDriverWait wait = new WebDriverWait (driver, 5);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("iMacs")));
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.presenceOfElementLocated(By.linkText("iMacs")));
waitForElementToBeDisplayed(driver.findElement(By.linkText("iMacs")), 200);
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[text()='iMacs']")));
This is my code:
WebElement element = driver.findElement(By.linkText("Product Category"));
Actions action = new Actions(driver);
action.moveToElement(element).perform();
WebDriverWait wait = new WebDriverWait (driver, 5);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("iMacs")));
WebElement subElement = driver.findElement(By.linkText("iMacs"));
action.moveToElement(subElement);
action.click();
action.perform();
This is my error:
org.openqa.selenium.TimeoutException: Expected condition failed: waiting for visibility of element located by By.linkText: iMacs (tried for 5 second(s) with 500 MILLISECONDS interval)
So you are hovering over some element and then trying to click on specific link? Which driver are you using? Do you actually see that this menu is correctly rendered after hover?
Your code fails on wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("iMacs")));
Try with wait.until(ExpectedConditions.presenceOfElementLocated(By.linkText("iMacs"))); instead and see if it fails then (and what exception it throws in that case).
And why are you using Actions API to perform click?
Please check the sendkeys option also. May be this help in your code.
driver.findElement(By.xpath("code']")).sendKeys("testdata");
I tried executing your code in Chrome and it always worked for me. However, as sometimes, it is failing for you, you can put recovery mechanism in your code, as shown below:
WebElement element = driver.findElement(By.linkText("Product Category"));
Actions action = new Actions(driver);
action.moveToElement(element).perform();
WebDriverWait wait = new WebDriverWait (driver, 5);
try {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("iMacs")));
} catch (WebDriverException we) {
System.out.println("First attempt to wait for visibility of 'iMacs' failed. Retrying...");
action.moveToElement(driver.findElement(By.linkText("Product Category"))).perform();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("iMacs")));
}
WebElement subElement = driver.findElement(By.linkText("iMacs"));
action.moveToElement(subElement);
action.click();
action.perform();
Above code should always work. Please let me know, if you have any further queries.

Why does not Explicit Wait work for autosuggest boxes?

I tried to use ExplicitWait for an autosuggest box but it did not work, so I am using simple Thread.sleep(5000):
/***************************************************************************************/
// The below Thread.sleep(5000) works fine
// Thread.sleep(5000);
// However the below Explicit Wait block does not recognize the element
WebDriverWait wait5000 = new WebDriverWait(driver, 0);
wait5000.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[#class='auto_suggest']/*[#class='title_item']")));
/***************************************************************************************/
WebElement firstItem = driver.findElement(By.xpath("//*[#class='auto_suggest']/*[#class='title_item']"));
firstItem.click();
System.out.println("Done!");
}
}
I can use Thread.sleep(5000) but this is not efficient, because of time loss. Is there any way to introduce an explicit wait for the autosuggest box? How to click the autosuggest box more in a more efficient way?
The 2nd parameter in the constructor is the timeout in milliseconds.
Here WebDriverWait wait5000 = new WebDriverWait(driver, 0); you are passing in 0 - you are giving it a maximum of 0 milliseconds to find the element. You could try increasing the timeout, for example, let it search for the element for up to 5 whole seconds:
WebDriverWait wait5000 = new WebDriverWait(driver, 5000);