We are going to present how you can mouseover an web element using Selenium WebDriver. The code below is straight forward:
- first we identify the element to be hovered in the web page, here is how you can find web elements using Selenium WebDriver.
- hover (mouseover) functionality is provided in Selenium WebDriver with the help of the Actions class, which provides the ability to move the mouse over an element.
WebElement web_Element_To_Be_Hovered = webDriver.findElement(By.cssSelector(selector_For_Web_Element_To_Be_Hovered)); Actions builder = new Actions(getDriver()); builder.moveToElement(web_Element_To_Be_Hovered).build().perform();
The build() method generates a composite action containing all actions so far, ready to be performed (and resets the internal builder state, so subsequent calls to build() will contain fresh sequences).
Also, if we want to click a web element after hovering the first element, we can do that by waiting for the element to be clickable, in order to interact with it.
WebDriverWait wait = new WebDriverWait(driver, 5); wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(selector_For_Element_To_Be_Click_After_Hover))); driver.findElement(By.cssSelector(selector_For_Element_To_Be_Click_After_Hover)).click();
The most important part is identifying the element right after the first web element was hovered (mouseover), otherwise we’ll get an exception that the element is not available.
Basically, you use the Actions to hover and the standard WebDriver method click, this way you could hover and then click.
Selenium WebDriver provides multiple options to interact with web elements with the Actions class. In our case, for mouseover (hover) functionality we can use the following 3 methods:
Moves the mouse to an offset from the top-left corner of the element
moveToElement(WebElement toElement, int xOffset, int yOffset)
Moves the mouse from its current position (or 0,0) by the given offset. If the coordinates provided are outside the viewport (the mouse will end up outside the browser window) then the viewport is scrolled to match.
moveByOffset(int xOffset, int yOffset)
Performs a context-click at middle of the given element. First performs a mouseMove to the location of the element.
With LoadFocus.com you can easily automate the repetitive manual testing of your site, schedule your automated tests to run from cloud instances at scheduled times.
We’ll notify you if something goes wrong on Slack or by Email. View detailed test reports with screenshots and videos of the bug in action
Thanks for reading. I hope you learned something interesting about React!
If you found this article useful, please share it with others. Don’t forget to subscribe to get notified for the upcoming articles.