A common case in a JavaScript based CMS is that it creates multiple elements with the same id or class on the same page. Usually only one element is displayed, and usually we have to cover situations when we have to interact with that exact item.
If we use the whole XPath or CSS locator we loose much of the flexibility, and the test can fail even after simple changes in the DOM.
To make the test a bit more flexible we can use the following technique to click on it:

public void clickLocation() {
 waitForElementToPresentInDom(By.cssSelector("span.locations"));
 Boolean clicked = false;
 List<WebElement> variableButtons = driver.findElements(By.cssSelector("span.locations"));
 for (WebElement button : variableButtons){
  if (button.isDisplayed()){
   button.click();
   clicked = true;
   break;
  }
 }
Assert.assertTrue("Not a single location button was visible", clicked);
}

First we check for the specified element if present in the DOM, if it is present then we list through the items and click on the visible one.
To check if the click was a successful, we can add a boolean variable and check its value.

Similar Posts from the author: