Are there situations where an ExplictWait is not working? - selenium-webdriver

I know about the three different types of waiting you can use in Selenium. I know why Thread.Sleep and ImplicitWait are never a good choice. So I'm always using ExplicitWaits, for instance to wait till a button is clickable. However, from time to time one or two tests in a collection of hundred tests fails because the Explictwait seems to fail.
I read the very interesting article: https://bocoup.com/weblog/a-day-at-the-races
about the reason why tests can fail from time to time and Explicit wait as the solution for this intermittent failures. This made me even more convinced about using ExplictWaits.
So I wonder is there anybody who knows situations were an Explicitwait is not doing the right job.
This is my C# code for waiting till a Webelement is clickable:
public static Boolean waitElementToBeClickable(IWebDriver driver, int seconds, IWebElement webelement)
{
Boolean clickable = true;
try
{
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(seconds));
wait.Until(ExpectedConditions.ElementToBeClickable(webelement));
}
catch
{
clickable = false;
}
return clickable;
}

Related

Is there a way to do an "if I see, then…" with webdriver acceptance testing?

I'm using webdriver for acceptance testing. https://codeception.com/docs/03-AcceptanceTests#WebDriver
I'm running into a thing where depending on if new features are launched, a popup will sometimes be there to notify the user of the new features. So that popup may or may not be there depending on where we are in the release cycle. Is there a way to say: "If I see , click Close" ?
You didn't say which programming language you are using, but the following in Groovy (Java) checks for an alert/modal popup. You can dismiss it in the method or use the return value in an if statement.
You should be able to adapt it for your language.
def isAlertPresent(driver){
boolean foundAlert = false
WebDriverWait wait = new WebDriverWait(driver, 10) //time-out secs
try {
wait.until(ExpectedConditions.alertIsPresent())
foundAlert = true
} catch (TimeoutException e) {
foundAlert = false
}
return foundAlert
}
Did you checked out if Cucumber.io and Gherkin syntax works for you?
With Gherkin you’ll be able to do everything you want.

Clarification on how Codename One UITimer works

I need a clarification about the Codename One UITimer.
For example, if I want to execute the same code every two seconds, a code like UITimer.timer(2000, true, () -> { do something; }); works until the user stays in the current Form? Is that right?
If I want to execute the same code every two seconds regardless the shown Form, have I to use something different from UITimer, like a custom separate thread? For example the following code?
Form hi = new Form("Hi World", BoxLayout.y());
hi.add(new Label("Hi World"));
hi.show();
EasyThread.start("MyTimer").run(() -> {
boolean executeMe = true;
while (executeMe) {
Log.p("Do something every two seconds...");
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Log.p("Stopping the EasyThread \"MyTimer\" because an exception");
Log.e(ex);
executeMe = false;
}
}
});
Moreover, if I execute this example code, the first logged line is:
[MyTimer] 0:0:0,59 - Codename One revisions: 8b451ecb7bfbe60baf91006441e7d7d9c46afe09
Why is that line logged by my custom thread instead of by the EDT?
Yes, UITimer is an animation associated with the current Form. It doesn't draw anything but uses the builtin animation mechanism which runs on the EDT. Notice that if you leave a form and return to it the timer will continue e.g.:
Opened form at 0 time and set a timer for 15 seconds
Went to different form at 7 seconds
Returned to original after 30 seconds - the timer will fire immediately on return
You can also use a regular Timer or Thread. However, for your specific code EasyThread doesn't provide a benefit over a regular thread since it runs in an infinite loop. The benefit of EasyThread is in it's job processing ability.
Notice that you would need to use callSerially to return to the EDT when working with such timers/threads.

Element ... is not clickable at point (35, 37) [duplicate]

I am trying to make some tests using selenium based Katalon Studio. In one of my tests I have to write inside a textarea. The problem is that I get the following error:
...Element MyElement is not clickable at point (x, y)... Other element would receive the click...
In fact my element is place inside some other diva that might hide it but how can I make the click event hit my textarea?
Element ... is not clickable at point (x, y). Other element would receive the click" can be caused for different factors. You can address them by either of the following procedures:
Element not getting clicked due to JavaScript or AJAX calls present
Try to use Actions Class:
WebElement element = driver.findElement(By.id("id1"));
Actions actions = new Actions(driver);
actions.moveToElement(element).click().build().perform();
Element not getting clicked as it is not within Viewport
Try to use JavascriptExecutor to bring the element within Viewport:
JavascriptExecutor jse1 = (JavascriptExecutor)driver;
jse1.executeScript("scroll(250, 0)"); // if the element is on top.
jse1.executeScript("scroll(0, 250)"); // if the element is at bottom.
Or
WebElement myelement = driver.findElement(By.id("id1"));
JavascriptExecutor jse2 = (JavascriptExecutor)driver;
jse2.executeScript("arguments[0].scrollIntoView()", myelement);
The page is getting refreshed before the element gets clickable.
In this case induce some wait.
Element is present in the DOM but not clickable.
In this case add some ExplicitWait for the element to be clickable.
WebDriverWait wait2 = new WebDriverWait(driver, 10);
wait2.until(ExpectedConditions.elementToBeClickable(By.id("id1")));
Element is present but having temporary Overlay.
In this case induce ExplicitWait with ExpectedConditions set to invisibilityOfElementLocated for the Overlay to be invisible.
WebDriverWait wait3 = new WebDriverWait(driver, 10);
wait3.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("ele_to_inv")));
Element is present but having permanent Overlay.
Use JavascriptExecutor to send the click directly on the element.
WebElement ele = driver.findElement(By.xpath("element_xpath"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", ele);
I assume, you've checked already that there is no any other component overlapping here (transparent advertisement-iframes or some other component of the DOM => seen quite often such things in input/textfield elements) and, when manually (slowly) stepping your code, it's working smoothly, then ajax calls might cause this behaviour.
To avoid thread.sleep, try sticking with EventFiringWebDriver and register a handle to it.
(Depending on your application's techstack you may work it for Angular, JQuery or wicket in the handler, thus requiring different implementations)
(Btw: This approach also got me rid of "StaleElementException" stuff lots of times)
see:
org.openqa.selenium.support.events.EventFiringWebDriver
org.openqa.selenium.support.events.WebDriverEventListener
driveme = new ChromeDriver();
driver = new EventFiringWebDriver(driveme);
ActivityCapture handle=new ActivityCapture();
driver.register(handle);
=> ActivityCapture implements WebDriverEventListener
e.g. javascriptExecutor to deal with Ajax calls in a wicket/dojo techstack
#Override
public void beforeClickOn(WebElement arg0, WebDriver event1) {
try {
System.out.println("After click "+arg0.toString());
//System.out.println("Start afterClickOn - timestamp: System.currentTimeMillis(): " + System.currentTimeMillis());
JavascriptExecutor executor = (JavascriptExecutor) event1;
StringBuffer javaScript = new StringBuffer();
javaScript.append("for (var c in Wicket.channelManager.channels) {");
javaScript.append(" if (Wicket.channelManager.channels[c].busy) {");
javaScript.append(" return true;");
javaScript.append(" }");
;
;
;
javaScript.append("}");
javaScript.append("return false;");
//Boolean result = (Boolean) executor.executeScript(javaScript.toString());
WebDriverWait wait = new WebDriverWait(event1, 20);
wait.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return !(Boolean) executor.executeScript(javaScript.toString());
}
});
//System.out.println("End afterClickOn - timestamp: System.currentTimeMillis(): " + System.currentTimeMillis());
} catch (Exception ex) {
//ex.printStackTrace();
}
}
As #DebanjanB said, your button (or another element) could be temporarily covered by another element, but you can wait and click it even if you don't know which element is covering the button.
To do this, you can define your own ExpectedCondition with the click action:
public class SuccessfulClick implements ExpectedCondition<Boolean> {
private WebElement element;
public SuccessfulClick(WebElement element) { //WebElement element
this.element = element;
}
#Override
public Boolean apply(WebDriver driver) {
try {
element.click();
return true;
} catch (ElementClickInterceptedException | StaleElementReferenceException | NoSuchElementException e) {
return false;
}
}
}
and then use this:
WebDriverWait wait10 = new WebDriverWait(driver, 10);
wait10.until(elementToBeClickable(btn));
wait10.until(new SuccessfulClick(btn));
Try Thread.Sleep()
Implicit - Thread.Sleep()
So this isn’t actually a feature of Selenium WebDriver, it’s a common feature in most programming languages though.
But none of that matter.
Thread.Sleep() does exactly what you think it does, it’s sleeps the thread. So when your program runs, in the majority of your cases that program will be some automated checks, they are running on a thread.
So when we call Thread.Sleep we are instructing our program to do absolutely nothing for a period of time, just sleep.
It doesn’t matter what our application under test is up to, we don’t care, our checks are having a nap time!
Depressingly though, it’s fairly common to see a few instances of Thread.Sleep() in Selenium WebDriver GUI check frameworks.
What tends to happen is a script will be failing or failing sporadically, and someone runs it locally and realises there is a race, that sometimes WedDriver is losing. It could be that an application sometimes takes longer to load, perhaps when it has more data, so to fix it they tell WebDriver to take a nap, to ensure that the application is loaded before the check continues.
Thread.sleep(5000);
The value provided is in milliseconds, so this code would sleep the check for 5 seconds.
I was having this problem, because I had clicked into a menu option that expanded, changing the size of the scrollable area, and the position of the other items. So I just had my program click back on the next level up of the menu, then forward again, to the level of the menu I was trying to access. It put the menu back to the original positioning so this "click intercepted" error would no longer happen.
The error didn't happen every time I clicked an expandable menu, only when the expandable menu option was already all the way at the bottom of its scrollable area.

WebDriver wait until this or that element is found

In one of the application workflows I have more than 10 pages to navigate.
I have to keep clicking on the 'Next' button continuously - it makes an AJAX call to re-load new content and 'Next' button will also be reloaded.
The number of pages to navigate is not always 10. It might be anything from 10-100.
My test will be complete whenever there is a webelement found with the id 'testcomplete'.
So Currently i use ExpectedConditions()
WebDriverWait wait = new WebDriverWait(driver, 30);
//Keep clicking next
while(isNextPresent()){
NextButton.click();
}
//testcomplete reached here
System.out.println("test complete");
private boolean isNextPresent(){
try{
WebElement element = wait.until(ExpectedConditions.visibilityOf(NextButton));
return true;
}catch(Exception e){
//
}
return false;
}
Currently my code works fine. But i am trying to improve it. I hate the unnecessary wait of 30 seconds when the element with the id 'testcomplete' is present. Because that time 'NextButton' will not be present.
How can I improve this isNextPresent function? Ie, to return false immediately when there is 'testcomplete' instead of waiting for 30 seconds?
Note: I have tagged protractor as well because I also have a similar requirement in protractor.
You can combine the conditions of both elements and take an action depending on the fact which one first returns true for 'visibilityOf(myElement)'. Maybe something like this in pseudo (sorry, no IDE around):
loop(i < 30){
// wait NextBtn for 1 sec, if true click and break
// wait TestCopmlete for 1 sec
}
Use EC.or(), a la:
wait.until(ExpectedConditions.or(
ExpectedConditions.visibilityOf(NextButton),
ExpectedConditions.visibilityOf(element(by.id('testcomplete')))
));
Then after this comes back, expect the desired state:
expect(NextButton.isDisplayed()).toBeTruthy();

IEDriver implementation fails the test

I am using Webdriver(without IEDriver implementation) 2.23 API on windows7 machine with JDK7 and JRE7. The test scripts are working fine as expected but when i introduced IEDriver the script fails in a page with cannot click on element error message as that corresponding element is not visible. i have double checked with my application for the locator. The same can be clicked with out IEDriver implementation. I have tried by simulating all the click types including context click by Action class. No use. All click types returns the same result. Any help ?
Finally, i was manage to click the above said Element with the help of following code.
WebElement we = driver.findElement(By.name("Complete"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", we); // common for all we
The real source is here. This may helpful for someone.
As you say that the element is actually visible and the error's log says it is not, I think that the problem might be due to Internet Explorer's slowness. You could use this method for a quick test:
boolean isElementDisplayed(final WebDriver driver, final WebElement element, final int timeoutInSeconds) {
try {
ExpectedCondition condition = new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(final WebDriver webDriver) {
return element.isDisplayed();
}
};
Wait w = new WebDriverWait(driver, timeoutInSeconds);
w.until(condition);
} catch (Exception ex) {
//if you get here, it's because the element is not displayed after timeoutInSeconds
return false;
}
return true;
}
Use it like this:
WebElement we = driver.findElement(By.name("Complete"));
if (isElementDisplayed(driver, we, 30)) {
we.click();
}
This will make the driver wait (30 sec max.) till the element we becomes visible and then the driver clicks on it.
If it works, then my supposition is right and you could change the method for:
void clickOn(final WebDriver driver, final WebElement element, final int timeoutInSeconds) {
try {
ExpectedCondition condition = new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(final WebDriver webDriver) {
element.click();
return true;
}
};
Wait w = new WebDriverWait(driver, timeoutInSeconds);
w.until(condition);
} catch (Exception ex) {
//probably some kind of exception thrown here
}
return;
}
and use it instead of we.click(), like:
WebElement we = driver.findElement(By.name("Complete"));
clickOn(driver, we, 30);
The code above is an approximation to let you check your issue in a quick and clear way and, if you end up using it, you should adapt it to your structure of code. This kind of utility code should never appear in your tests. Your test code should be clean and the same for all the environments (browsers, version, SOs, etc.). Keep the workarounds separately, e.g. some kind of util package.
Also, the method's signature is 'overweight'. Restructuring your util code, you should be able to write in your tests just this: clickOn(element).
Hope it helps ;)
UPDATE Actually, with these components I had never run into a similar problem:
selenium-server-standalone version 2.32.0
IEDriverServer_x64_2.30.1.exe

Resources