Selenium C# Tutorial: Checking an element's status (C#)

Updated: Jan 18

It is a widespread scenario that tests fail to enter text in a field or click on an element because it is disabled or exists in the DOM but is not displayed on the page. In this case, the test will fail as an error bring thrown. Robust error handling is needed in the test flow to build reliable test cases that can run unattended.

We can do it by using the WebElement class, which provides unique methods to check the current state of an element:

  • isEnabled() - This method checks if an element is enabled (Returns true if enabled, false for disabled).

  • isSelected() - This method checks if element is selected (e.g. checkbox, radio button, etc) It returns true if selected, else false for deselected.

  • isDisplayed() - This method checks if element is displayed.

Code Examples:


isDisplayed()

[TestMethod]
public void IsDisplayed_Ex1()
{
tmpElement = driver.FindElement(By.CssSelector("#img_2_comp-khbyvzck4 > img:nth-child(1)"));            
bool Element_Displayed = tmpElement.Displayed;
Assert.IsTrue(Element_Displayed);       
}
        
[TestMethod]
public void IsDisplayed_Ex2()
{
tmpElement = driver.FindElement(By.CssSelector("#img_2_comp-khbyvzck4 > img:nth-child(1)"));
 bool Element_Displayed = tmpElement.Displayed;           
         
if (Element_Displayed == true)
{
Console.WriteLine(tmpElement.GetAttribute("alt"));
}
else
{
driver.Quit();
}
}

Result:


isSelected() & isSelected()

Using the isEnabled () method will check for the "Disabled" attribute of an element. If the attribute "Disabled" does not exist, it will return the result of 'True.' Therefore, if you have an element that is disabled but does not contain this attribute, the return value will always be 'True'

[TestMethod]
        public void IsSelectedAndEnabled()
        {
            //Step 1: Check if an element is Enabled
            tmpElement = driver.FindElement(By.Id("flexCheckDefault"));

            if (tmpElement.Enabled == true)
            {
                //Step 2: Check if an element is Selected
                if (tmpElement.Selected == false)
                {
                    tmpElement.Click();
                }
            }
            else
            {
                driver.Quit();
            }



60 views0 comments