Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium Webdriver C# How to test an element is not present?

This element can be found when a required field has been filled out:

IWebElement e1SK = Driver.Instance.FindElement(By.XPath(baseXPathSendKeys + "div[2]/textarea"));

When the required field is not filled in, the above element should not be present.

The test throws an exception:

OpenQA.Selenium.ElementNotVisibleException: Element is not currently visible and so may not be interacted with

Is this something I need to create a method for or is it even more simple than that? If you could show an example, it would be helpful, I'm still fairly new to C# and Selenium Webdriver.

I have read that I might be able to user something called findwebelements then checking to make sure the result has a length of zero, but am not sure how to implement that either.

like image 693
MattJ Avatar asked Dec 01 '22 18:12

MattJ


1 Answers

Here's a straightforward approach to the problem:

if (Driver.Instance.FindElements(By.XPath(baseXPathSendKeys + "div[2]/textarea")).Count != 0)
{
    // exists
}
else
{
    // doesn't exist
}

You could create a method Exists(By) to test elements:

public bool Exists(By by)
{
    if (Driver.Instance.FindElements(by).Count != 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

Then call it when you want to test something:

By by = By.XPath(baseXPathSendKeys + "div[2]/textarea")
if (Exists(by))
{
    // success
}
like image 131
Richard Avatar answered Dec 05 '22 05:12

Richard