Search code examples
c#seleniumappium

Appium - Check if element exist


I am trying to check if an element exist or not in my application (React Native) with Appium (C#). I beleive using .Displayed is the best practice for this, however, this throws an NoSuchElementException when the element does not exist.

The only workaround I can think of for this is to wrap the .FindElement* method with a try/catch. Is this the best method for checking if an element exist, or am I missing a better approach?

enter image description here

private AndroidElement Name => Driver.FindElementByXPath("//*[@text='John Doe']");

public void OpenMenu()
{
    Utils.Log("Opening menu");
    if (!Name.Displayed)
        ToggleButton.Click();
}

Thanks!


Solution

  • .Displayed tells you whether the element is visible, not present/exists. The reason it's throwing is because when the element is not there, your .Find* fails. You would also get false negatives if the element was present but not visible. Best practice in cases like this is to use the plural form of .Find*, e.g. FindElementsByXPath(), and check to see if the collection is empty. If it's not empty, the element is present.

    private IEnumerable<AppiumWebElement> Name => Driver.FindElementsByXPath("//*[@text='John Doe']")
    

    Then to check if the collection is empty

    // requires LINQ
    if (Name.Any())
    {
        // element exists, do something
    }
    

    If you don't want to use LINQ

    if (Name.Count() > 0)
    

    Per the Appium docs, you should avoid using XPath.

    XPath | Search the app XML source using xpath (not recommended, has performance issues)