MouseHover in C# Selenium for any Element

Many a times we may just need to verify whether the sub menus are displayed when we hover over a mousemenu  like shown below

 

In the above picture we may have to verify whether these submenus Space,Energy,Health and Environment are displayed when we hover our mouse over Science without clicking it.

Selenium doesn’t provide any default mouse hover functionality but we can use Actions and Perform to accomplish the task of MouseHover over a menu

//Menu XPath is the XPath of menu for which you have to perform a hover operation
public void JustMouseHover(String MenuXPath)
{
                              
            WebDriverWait wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(10));
            var element = wait.Until(ExpectedConditions.ElementIsVisible(By.XPath(MenuXPath)));
            Actions action = new Actions(Driver);
            action.MoveToElement(element).Perform();   
            //Waiting for the menu to be displayed    
            System.Threading.Thread.Sleep(4000);
}

In the above code,

  • We need to pass the XPath of the menu or an element for which we are trying to perform a mouse hover
  • It make uses of wait statement to look for menu element on which we are doing a mouse hover
  • Then it using Actions to do the hover.

 

 

 

 

You may also like...