Stop Moving So I Can Click You Dammit!

This entry was posted by on Sunday, 24 February, 2013 at

This is a little trick that some may find useful.

I re-factored some tests that were checking an accordion control on Friday to speed things up, unfortunately when I was done I started getting some intermittent failures.  It seemed that I was now sometimes unable to open up one of the accordion elements.  A bit of head scratching and some time in the debugger with nothing obvious jumping out at me I finally realised what it was.  I was sometimes clicking on an element to open up the next accordion whilst it was still moving (all because I made things run faster).  

The solution? Wait until the element has finished moving.

Hers is an Expected condition that you can use with WebDriverWait:

public static ExpectedCondition<Boolean> elementHasStoppedMoving(final WebElement element) {
    new ExpectedCondition<Boolean>() {
        @Override
        Boolean apply(WebDriver driver) {
            Point initialLocation = ((Locatable) element).getCoordinates().inViewPort();
            Thread.sleep(50);
            Point finalLocation = ((Locatable) element).getCoordinates().inViewPort();
            initialLocation.equals(finalLocation);
        }
    }
}

5 Responses to “Stop Moving So I Can Click You Dammit!”

  1. Nick

    I’m pretty new with WebDriverWait, how can I use your code with it ?
    Can you show me an exemple ?
    Thanks.

    • Ardesco

      You just need to use it in your wait object like so:

      WebElement movingElement = driver.findElement(By.id("foo"));
      WebDriverWait wait = new WebDriverWait(driver, 15, 100);     
      wait.until(elementHasStoppedMoving(movingElement));
  2. uriel avalos

    Unfortunately, this isn’t a general solution as the timeout may not be sufficient for other properties and/or other UI frameworks. For example, it may take longer than 50 milliseconds for the height property to change and the timeout is probably a function of the browser.

    • Ardesco

      You misunderstand the code, it checks to see if the location has changed every 50ms, the timeout will be whatever you set the timeout to be on your explicit wait.

Trackbacks/Pingbacks

  1. A Smattering of Selenium #145 | Official Selenium Blog

Leave a Reply




eight − = six