Hugh McCamphill
Hugh McCamphill's Blog

Hugh McCamphill's Blog

Waiting for an element to stop moving

Waiting for an element to stop moving

Hugh McCamphill's photo
Hugh McCamphill
·Feb 12, 2022·

2 min read

Sometimes with Selenium and libraries or frameworks that use it, we need to wait for an element to stop moving before attempting to click on it (to not enconter StaleElementReferenceExceptions, for example). One approach to wait for the element to stop moving is to query it's location and check this twice, with a small sleep between the calls. If the location of the element is the same both times, then we can consider the element to have stopped moving.

The most appropriate way to implement this will differ with languages and libraries, but WebDriverIO provides a nice way to encapsulate this with Custom Commands

browser.addCommand(
      "waitUntilStopMoving",
      function () {
        browser.waitUntil(
          () => {
            this.waitForDisplayed();
            let initialLocation = this.getLocation();
            let initialX = initialLocation.x;
            let initialY = initialLocation.y;
            browser.pause(200);
            let finalLocation = this.getLocation();
            let finalX = finalLocation.x;
            let finalY = finalLocation.y;
            return initialX === finalX && initialY === finalY;
          },
          {
            timeout: 5000,
            timeoutMsg: "expected element to have stopped moving",
          }
        );
      },
      true
    );

If we add the custom command to before in the wdio.config.js

/**
   * Gets executed before test execution begins. At this point you can access to all global
   * variables like `browser`. It is the perfect place to define custom commands.
   * @param {Array.<Object>} capabilities list of capabilities details
   * @param {Array.<String>} specs List of spec file paths that are to be run
   */
  before: function (capabilities, specs) {

We can then call the custom command quite simply before clicking the element

$('div.confirm').waitUntilStopMoving();
$('div.confirm').click();

Did you find this article valuable?

Support Hugh McCamphill by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
 
Share this