WebDriver - click on non-clickable element

My team and I had a lot of trouble clicking on LI and SPAN elements (using UI library that has components like that) and got an error that is is not clickable element. So we had to find a workaround and what we found out is good way to click on non-clickable element, so we created helper function to do call where we need it:

   /**
   * Click element found by XPath selector.
   * If position is passed, check all elements found with selector.
   * Position should start with 1, not 0.
   *
   * @param {string} selector   XPath selector for the element
   * @param [position] {number}   If there are more elements, select one on this "position" (starts from 1)
   * @returns {PromiseLike<void | never>}
   */
  clickElement(selector, position) {
    const WebDriver = this.helpers['WebDriver'];
    return WebDriver._locate(selector, true).then(elements => {
      if (position) {
        return elements[position - 1].click();
      } else {
        return elements[0].click();
      }
    });
  }

This doesn’t block flow and CodeceptJS neatly picks returned Promise and continues execution. Only pitfall is that we had to use XPath (didn’t try with other selector types).

Any comments and improvements are welcome.

2 Likes

Thanks for the tip! Looks useful.

Few points here:

  • _locate accepts both XPath and CSS.
  • You can also use _locateClickable to find buttons or links by their text like regular click does.

Thanks, good to know about CSS.

BTW, isn’t I.click() using _locateClickable()?

We were actually trying to avoid looking for buttons an links but click on spans, divs etc. so we come up with this solution. :slight_smile: