How to Handle Mouse Actions in Selenium

Faisal Khatri

Posted On: September 13, 2024

view count321884 Views

Read time16 Min Read

While automating a website using Selenium, you can realize specific scenarios by automating low-level interactions such as keypresses and mouse button actions with the WebElements in the Document Object Model (DOM).

Implementing Selenium tests that involve automating actions like accessing drop-down boxes and clicking or double-clicking on a button requires good know-how of the Actions class in Selenium. At a broad level, the Actions class comprises keyboard and mouse actions, but our focus would be on mouse actions in Selenium.

What Are Mouse Actions in Selenium?

Mouse actions in Selenium provide a mechanism for automating low-level elementary interactions such as mouse clicks, mouse hover, and mouse button actions. It also helps with automating complex low-level interactions such as mouse hover, drag and drop, click and hold, and more.

Here is a brief list of methods for handling mouse actions that are provided by the Actions class in Selenium:

  • click() method
  • doubleClick() method
  • clickAndHold() method
  • contextClick() method
  • dragAndDrop() method
  • moveToElement() method
  • moveByOffset() method
  • release() method

Subscribe to the LambdaTest YouTube Channel for more such tutorials.

Handling Mouse Actions in Selenium

Now that we have known the methods for mouse actions in Selenium, let’s look at how to implement them.

Implementation:

Import the package org.openqa.selenium.interactions.Actions. Then, create an object of the Actions class and pass the Selenium WebDriver instance to the object.

Use the object to access the methods for automating mouse-related operations in the Selenium script.

Selenium script

We will use the TestNG framework and Selenium 4. At the time of writing this blog, the latest version of Selenium WebDriver in place was 4.23.1

The pom.xml file is used for downloading the requisite packages from the Maven repository. The respective tests are executed on cloud testing platforms like LambdaTest. It is an AI-driven test execution platform that lets you test mouse actions with Selenium online on various browsers and operating systems. It helps ensure consistent behavior of mouse interactions across different environments, reducing the need for local infrastructure.

You get access to your Username and Access Key from your LambdaTest Account Settings > Password and Security. Also, the automation capabilities can be generated using the LambdaTest Automation Capabilities Generator.

A new mouseactionsdemo package has been created inside the src/test folder that will have all the demo test scenarios for handling mouse actions in Selenium.

Here is the implementation of the methods under the @BeforeTest and @AfterTest annotations. The methods used for demonstrating mouse actions in Selenium should be included under the @Test annotation.

github

The setup() method that has the @BeforeTest annotation over it will set up the configuration for running the tests on the LambdaTest cloud grid. The getChromeOptions() method will pass on the required capabilities for running the tests on the Chrome browser.

Likewise, the tearDown() method that has the @AfterTest annotation will close the WebDriver session gracefully.

Now, let’s look at different types of mouse actions in Selenium.

Single Click Action in Selenium

Single click is one of the basic mouse actions in Selenium that you will be required to perform during the Selenium test automation process. Left mouse clicks are primarily used to perform click actions on buttons, checkboxes, radio buttons, etc. When we refer to a mouse click, it is always the ‘left click’ since the right click opens up the context menu.

For more details about mouse click action, refer to this blog on the Selenium click button method.

In this blog, we will use the LambdaTest eCommerce Playground website for our test scenarios.

Test Scenario:

  1. Navigate to the LambdaTest eCommerce Playground website.
  2. Locate the search box and type the text iPhone.
  3. Click on the search button to perform the search operation.
  4. Check if the product is listed in the search.

Implementation:

A new testMouseClickAction() method has been added in the class TestMouseActions that implements the above test scenario.

Code Walkthrough:

The test navigates the user to the home page of the LambdaTest eCommerce Playground website. It locates the search box using the name locator strategy of Selenium and types the word iPhone in it.

The search button will be located next using the CSS Selector locator strategy, and a click action will be performed on the button using the click() method.

The page header will be located at the end, and its text will be stored in the pageHeader variable in string format using the getText() method of Selenium. Finally, an assertion will be performed to check that the page header equals Search- iPhone.

Test Execution:

The following screenshot of the test execution on the LambdaTest platform:

test execution

Double Click Action in Selenium

Double click mouse action in Selenium is one of the prime actions used for Selenium test automation.

Test Scenario:

  1. Navigate to https://unixpapa.com/js/testmouse.html.
  2. Double-click on click here to test.
  3. Search for dblclick in the text area.
  4. Assert if the double-click operation is not successful.

Implementation:

A new testDoubleClickAction() method has been created in the existing TestMouseActions class to implement the test scenario.

Code Walkthrough:

This test script locates the click here to test link after navigating to the website. Next, the Actions class by Selenium performs a double-click action on the link.

The text box that shows the click action information is located using the tagName locator strategy and the CSS attribute value.

The last statement of the code performs an assertion to check that the text box contains the text dblclick in it.

Test Execution:

The following screenshot of the test execution on the LambdaTest platform:

test execution of the platform

Context Click Action in Selenium

Context menu (or browser context menu) is the menu that is available when the user does a right-click operation on a web page (or WebElement). The items in the context menu depend on the WebElement on which right-click is performed.

Test Scenario:

  1. Navigate to the Context Menus page of the LambdaTest Selenium Playground website.
  2. Right-click on the box provided on the screen.
  3. Verify the alert text You selected a context menu displayed on the right click.

Implementation:

A new testContextClickAction() method is added to the existing TestMouseActions class to implement the test scenario.

Code Walkthrough:

The above test script will locate the context click-box using the id locator hot-spot on the context menu page of the LambdaTest Selenium Playground website. Using the contextClick() method of the Actions class of Selenium WebDriver, the right-click action will be performed.

After the right click is performed, an alert message will be displayed, and the text of this message will be stored in the alertText variable in string format. Finally, an assertion will be performed to check that the alert text equals You selected a context menu.

Test Execution:

selected a context menu

Advanced Use Cases: Mouse Actions in Selenium

In the above section, we discussed handling different types of mouse actions in Selenium, such as click, double-click, and context click. Now, let’s look at some more advanced use cases of mouse actions in Selenium.

Automate Slider Movement

For automating test scenarios where a WebElement like slider is involved, we have to use the moveByOffset() method with the X and Y coordinates to move the slider. The moveByOffset() method can also be used for clicking anywhere on the page where the offset is in the form of an X and Y coordinate pair.

Let’s consider the following test scenario for demonstrating the slider movement using moveByOffset() in Selenium.

Test Scenario:

  1. Navigate to the Slider Demo page of the LambdaTest Selenium Playground website.
  2. From the current default value of 5, drag and move the slider to value 20.
  3. Check that the output value is displayed correctly after the slider is moved.

Implementation:

For moving the slider horizontally, we have to perform the following set of mouse actions:

  1. Click and hold the slider element.
  2. Move the slider element by the specified offset using the moveByOffset() method.
  3. Release the mouse at the resultant X and Y position.
  4. Perform the set of actions.

The test scenario has been implemented by creating a new testSliderAction() in the existing TestMouseActions class.

Code Walkthrough:

The slider on the Slider Demo page is located using the CSS Selector locator strategy combining the type and value attributes. Now, as we need to drag the slider using the offset, we need the X and Y coordinates of the slider.

Hence, we will be retrieving the X and Y coordinates of the slider using the getX() and getY() methods of the point class. We can then use the Y coordinates to drag the slider using the moveByOffset() method from the Actions class.

When we execute the test, the X and Y coordinates are printed in the console as X: 60 and Y: 282.

execute the test

These coordinates are actually the points in the center of the slide. So, in order to move the slide to 20, we need to provide a negative value of -145 in the offset X coordinate (value between 0 and -282 as point 282 is the center, i.e., 50). Similarly, if we need to move the slider above 50, then we need to provide positive values between 0 to 282.

We will be chaining the actions, i.e., click and hold, moveByOffset() method, and then release the mouse to drag the slider. This chaining will be performed using the Actions class in Selenium.

After the slider is dragged successfully, an assertion will be performed to check that the slider was dragged successfully to 20 pixels.

Test Execution:

Shown below is the position of the slider element before the test is executed:

position of the slider element

Here is a snapshot that indicates that the slider element has moved by an offset of (-145, 0). It is just before the release operation is performed, due to which the slider element is still in focus.

release operation

The test execution details with video and screenshots can be found on the LambdaTest Web Automation Dashboard page.

Web Automation Dashboard

Drag and Drop Operation

There are scenarios in Selenium web automation where you will need to drag a WebElement and drop it at the target location. Here the location where you need to drop the element is prominent in the UI so that the user has complete visibility about where the source element has to be dropped.

There are three methods that can be used to carry out a drag-and-drop operation using the Actions class in Selenium:

Let’s look at each of these approaches that demonstrate mouse actions in Selenium for the following test scenario:

  • dragAndDrop() method
  • clickAndHold() and moveToElement() methods
  • dragAndDropBy() method

Test Scenario:

  1. Navigate to the Drag and Drop Demo page of the LambdaTest Selenium Playground website.
  2. Drag the Draggable 1 item and drop it to the Drop here box.
  3. Assert that the Dropped Items List shows the Draggable 1 under it.

dragAndDrop() Method

In this method, we will be using the dragAndDrop() method of the Actions class to drag and drop the WebElement. Let’s create a new testDragAndDrop() method in the existing test TestMouseActions class to implement the test scenario.

Code Walkthrough:

The draggable item will be located using the CSS Selector locator strategy #todrag > span:nth-child(2) as there are two draggable items on the screen. CSS Selectors make it easy to locate the WebElements using the nth-child selector.

Next, the drop zone is located using the ID locator strategy. The dragAndDrop() method from the Actions class is used to perform the drag and drop action where we need to supply the draggable item as the source WebElement and drop zone as the target WebElement.

An assertion is finally performed to verify that the drag and drop actions were performed as required, where we check that the Dropped Item List has the value Draggable 1 in it.

Test Execution:

The following screenshot from LambdaTest Web Automation Dashboard shows the test execution details with a video of the test execution and different test steps.

execution details with a video

clickAndHold() and moveToElement() Methods

Let’s create a new testDragDropApproachTwo() method for implementing this approach in the existing test TestMouseActions class.

Code Walkthrough:

This script will navigate to the Drag and Drop Demo page and locate the draggable WebElement using the CSS Selector strategy. Next, it will locate the drop zone WebElement using the ID locator strategy.

The following lines of code will help in dragging and dropping of WebElements using clickAndHold() and moveToElement() methods.

Finally, it will perform the assertion to check that the Dropped Items List has the Droppable 1 WebElement in it.

Test Execution:

The following screenshot from LambdaTest Web Automation Dashboard shows the test execution details.

Drag and Drop Demo

dragAndDropBy() Method

Let’s create a new testDragDropApproachThree() method to implement the third approach and use the dragAndDropBy() method to implement the test scenario.

Code Walkthrough:

The script will navigate to the Drag and Drop Demo page, locating the draggable WebElement using the CSS Selector strategy. The drag and drop action will be performed using the dragAndDropBy() method of the Actions class.

This dragAndDropBy() method needs three parameters, i.e., source element, xOffset, and yOffset. The source element is draggable, which we located earlier. Now, to locate the X and Y offset, there is a quick tip that can be used.

source element is draggable

The X offset can be quickly located using the following steps:

  1. Locate the WebElement using the DevTools window in Chrome.
  2. On the right hand of the DevTools window, click on the Computed tab and check the center point of the WebElement. Currently, it shows 477.500 x 0.

We can use the X offset as 477 and Y offset as 0 for performing the drag and drop action. The following line of code will allow us to achieve the action we intend to perform.

drag and drop action

After the drag and drop action is complete, an assertion will be performed to check that the draggable item was moved to the correct drop zone.

perform assertion

Test Execution:

The following screenshots are of the test execution performed using IntelliJ IDE, showing that the drag-and-drop action was completed.

The test execution details can be found on the LambdaTest Web Automation Dashboard with video and other insights like logs, screenshots, test steps, etc.

video and other insights like logs, screenshots, test steps

Click a Link in Hover Menu

Here are the steps to automate clicking on a link that is inside the hover menu:

  1. Use the moveToElement() method to move the pointer to the WebElement containing the link in the hover menu.
  2. Trigger perform() method to execute the prepared action, making the hover menu visible.
  3. Locate the hover menu using the findElement() method.
  4. Use moveToElement() method again to move the pointer to the body of the hover menu.
  5. Locate the required link in the hover menu using a suitable locator (e.g., linkText).
  6. Wait for a certain duration using ExpectedConditions.presenceOfElementLocated, then perform a click() method on the located link, ensuring it is present in the DOM before proceeding.

You can also check out this blog to learn about mouse hover in Selenium.

Test Scenario:

  1. Navigate to the LambdaTest eCommerce Playground website.
  2. Hover the mouse over the ‘My account” menu on the home page and click on Login.
  3. Assert that the Login page is loaded successfully by checking the Page header text – Returning Customer.

Implementation:

Let’s create a new testMouseHover() method in the TestMouseActions class for implementing this test scenario.

Code Walkthrough:

The script navigates to the LambdaTest eCommerce Playground website and locates the My account link using the CSS Selector strategy. The mouse hover action will be performed using the moveToElement() method of the Actions class in Selenium WebDriver.

LambdaTest eCommerce Playground

The moveToElement() method takes the target element as the parameter, which in our case is the My account link. When the My account link is hovered over by mouse, the menu should open, and next the Login link will be located using the linkText locator strategy of Selenium WebDriver.

An assertion needs to be performed next to check that the Login page was navigated successfully after clicking on the Login link. The page header text on the Login page is located using the tagName locator strategy. As there are multiple h2 tags on this page, we will be using the findElements() method of locator that will return a list of WebElements.

Login link

Finally, an assertion is done to check that the page header text equals the text Returning Customer.

Test Execution:

The following screenshot from LambdaTest Web Automation Dashboard shows the test execution details.

Returning Customer

Wrapping Up!

Automation of low-level mouse interactions is one of the widely-used strategies in Selenium test automation. Action class in Selenium provides the necessary methods for automating mouse interactions on the web page.

In this detailed blog, we had a detailed look at how to perform mouse actions in Selenium and its different approaches. How do you leverage the Action class in Selenium to perform Selenium test automation? Try your hands on it and share your experience.

Frequently Asked Questions (FAQs)

How to use mouse actions in Selenium?

Selenium provides the Actions class to perform mouse actions like clicking, double-clicking, right-clicking, dragging, and hovering. You can use methods like moveToElement(), click(), and perform() to control these actions.

What are the actions of the mouse?

Mouse actions include clicking, double-clicking, right-clicking, hovering, dragging and dropping, scrolling, and clicking and holding. These actions allow users to interact with elements on a screen in various ways.

Can Selenium control a mouse?

Yes, Selenium can control a mouse using the Actions class, which simulates mouse movements and interactions with web elements, allowing automated testing of complex UI behavior.

Author Profile Author Profile Author Profile

Author’s Profile

Faisal Khatri

Faisal is a Software Testing Professional having 14+ years of experience in automation as well as manual testing. He is a QA, freelancer, blogger and open source contributor. He loves learning new tools and technologies and sharing his experience by writing blogs.

Blogs: 39



linkedintwitter

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free