How to perform mouse hover operation in Selenium
Hovering is a fundamental digital action that involves placing the mouse cursor on the target link or button. Users mainly use the mouse hover action to access sub-menu items. Submenus or sub-lists are standard for e-commerce websites like Amazon, Walmart, etc. This is a fundamental and frequently used action for more websites, and thus it must be created and tested to work perfectly for browsers and customers at all times.
In some instances, automating tests for child elements under sub-menus becomes challenging as they render in DOM only when the mouse hovers over the main (parent) element.
Thankfully, the hover operation can be automated in Selenium using the Actions class. This article will illustrate how one can automate the mouse hover operation in Selenium with relevant code snippets.
Performing Mouse Hover Operation in Selenium
Prerequisite: One needs to be familiar with the different locator strategies in Selenium to locate specific web elements before being able to automate the mouse hover.
The first step for hovering over an element is to locate that particular element. Then, the tester can perform the hover operation using the Actions class.
Refer to the code snippet below:
WebElement ele = driver.findElement(By.xpath("<xpath>"));//Creating object of an Actions class
Actions action = new Actions(driver);//Performing the mouse hover action on the target element.
action.moveToElement(ele).perform();
Now let’s explore the process to perform hover and click operation for elements in the sub-menu.
The first step here would be to locate the main menu (AKA parent menu). Once that is done, the second step is to locate the desired element (child element) from the available options in the sub-menu. The final step would be to click on that child element.
Refer to the code snippet below:
// Locating the Main Menu (Parent element)
WebElement mainMenu = driver.findElement(By.xpath("<Xpath of the Main menu"));//Instantiating Actions class
Actions actions = new Actions(driver);//Hovering on main menu
actions.moveToElement(mainMenu);// Locating the element from Sub Menu
WebElement subMenu = driver.findElement(By.xpath("<Xpath of the sub element>"));//To mouseover on sub menu
actions.moveToElement(subMenu);//build()- used to compile all the actions into a single step
actions.click().build().perform();
The code above first locates the parent element and hovers over it and as soon as the sub-menu renders, it locates the child element from the sub-menu, hover, and finally performs the click operation on it.
Identifying bugs is only possible when QA engineers interact with every single element on a website. For this, QA engineers need to replicate or simulate the end-user interactions by creating automated test scripts. The mouse hover operation in combination with the click command enables them to do this. This also helps QA teams comprehensively test and validate the functionality of web applications.