WebDriver: How to check if an page object web element exists?

Viewed 50044

How to check if an Element exists, when using Page Objects with webdriver.

So far I am doing it this way.

DefaultPage defaultPage = PageFactory.initElements(this.driver,
      DefaultPage.class);
assertTrue(defaultPage.isUserCreateMenuLinkPresent());

Page Object:

public class DefaultPage {     
    @FindBy(id = "link_i_user_create")
    private WebElement userCreateMenuLink;


    public boolean isUserCreateMenuLinkPresent() {
        try {
            this.userCreateMenuLink.getTagName();
            return true;
        } catch (NoSuchElementException e) {
            return false;
        }
    }
 }

But I can not believe that this try/catch is the way one should do it. So what would be a better way to check if the elements exits (with using Page Objects)?

9 Answers

Here is a nice pattern to access optional elements on a page:

@FindBy(...)
private List<WebElement> element;

public Optional<WebElement> getElement() {
    return element.stream().findFirst();
}

In a test, you could then use the following assertions:

assertEquals(Optional.empty(), page.getElement()); // element should be absent

assertTrue(page.getElement().isPresent()); // element should be present

var e = page.getElement().orElseThrow(AssertionFailedError::new); // check and use element
Related