2

I have a back button on my web page which I need to click on from different places.

In one page the back buttons xpath looks like: //property-list/ion-header/ion-navbar/button

In another other page it looks like: //select-client/ion-header/ion-navbar/button.

I'm using POM - can I use one object to identify all the xpaths my button could have?

1

I am giving my answer in Java:

You can identify the common parts of the xpath and use it in your locator.

As per your above mentioned sample xpath's you can do the following :

Using only POM:

By backButtonLocator = By.xpath(".//ion-header/ion-navbar/button");

public void clickonElement(By backButtonLocator)
{
  driver.findElement(backButtonLocator).click();
}

Using PageFactory:

@FindBy(how = How.XPATH, using =".//ion-header/ion-navbar/button")
public WebElement backButton;

public void clickonElement(WebElement ele)
{
  ele.click();
}
| improve this answer | |
  • Let me try this. – ChathuD Feb 28 '17 at 6:21
0

If the selector of the_coder doesnt work, I would suggest to let the developers add a better way to find it. For example by adding an ID.

Alternatively you could do something like:

back() {
  Boolean found = false;
  try {
    driver.findElement("//property-list/ion-header/ion-navbar/button").click();
    found = true;
  } catch {
   // Ignore notfoundexception
  }
  try {
    driver.findElement("//select-client/ion-header/ion-navbar/button").click();
    found = true;
  } catch {
   // Ignore notfoundexception
  }
  if (found === false) throw new Exception('backButtonNotFound');
}

Just try to click both different paths, if one succeeds it is OK, else throw an exception.

| improve this answer | |
  • Thanks Niels,but the thing is there can be 5 to 6 variations of the beginning tag.so do i have to add all xpath variations to your above logic ? – ChathuD Feb 28 '17 at 16:23
0

You can use something similar to the logic Niels has suggested.

You could also do something like the following in your page object:

// find my button - first, get all button elements on the page
// then use System.Linq to find the button in the collection
// with something in its innerHtml that only the back button will have
// Everything has been declared elsewhere in the unit.
try 
{
    button = driver.findElements(By.Type, "button").Where(c -> c.InnerHtml.Contains("Back").First();
}
catch (ElementNotFoundException e)
{
    // do something to handle not finding the button
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.