Performing Actions - Using the Actions Class


#1

Imagine you have the task of testing a modern web application like, for example, an e-commerce app. Today’s web applications have various functions and advanced features that require mouse hover to display the menu items, drag and drop to upload some files, context click etc.
Standard Selenium methods in these cases are not sufficient to perform some valid tests, so we call the Actions class for help.

Selenium has the built-in ability to handle various types of keyboard and mouse events. Webdriver has introduced advanced User Interactions API, which includes actions such as drag and drop or clicking multiple elements while holding down the Control key.

In order to do action events, you need to use org.openqa.selenium.interactions.Actions class.
The Action class is the user-facing API for emulating complex user action events. You can directly use this class rather than using the input devices, i.e. Keyboard or Mouse. It implements the builder pattern, in which a complex object is constructed that can be further used to create a different representation of the same object.

How to use the Actions class?

  1. First of all, we need to provide the selector of the element we want to perform actions on.

  2. The second step is to instantiate the actions class and pass in the WebDriver instance, so we can use all its methods. We simply call the action class:

Actions act = new Actions(driver);
  1. Call the required method from the Actions class and perform the action.

  2. Finally, add the .peform() command to complete your action and use it in the actual test.

    47

The complete step would look like this:

public ActionsPo doubleClickIt() {
      // Locate the element
      WebElement checkOutButton= this.wait.until(ExpectedConditions.visibilityOfElementLocated(this.checkOutButton));

      // Instantiate the Actions class
      Actions act = new Actions(driver);

      // Perform the Action
      act.doubleClick(checkOutButton).perform();

      return this;
}

You can find out more about the Action class, and further available actions here at the Selenium official documentation.


Check out our articles with examples on how to perform the following Actions using Ranorex Webtestit: