At times, while performing automated browser testing, you often have to deal with elements, which reveals only after you hover on the menu or after you click on them. In such cases, you can opt for using the action class for keyboard and mouse actions in Selenium Protractor. With the action class, you can automate the representation of mouse activities, such as mouse-clicking, mouse hovering, etc.
The Selenium Protractor framework has in-built capabilities to manage various forms of keyboard and mouse events. This handling of keyboard and mouse events is achieved using the Advanced User Interfaces API. These are web-based API for emulating complex movements performed by the user.
In this Protractor tutorial, I’ll take a look at various aspects of how to handle mouse and keyboard actions in the Selenium Protractor framework. Along with a few examples of the frequently used keyboard and mouse actions in Selenium Protractor. I’ve already covered how to run tests on Selenium with Protractor and what are the requirements for it in a previous article.
Mouse Actions in Selenium Protractor
Mouse actions are the representation of mouse activities, such as hover, drag, and drop, and clicking multiple elements. They can be easily simulated in Selenium Protractor with predefined methods for mouse movement, clicking, and others.
The following are some of the mouse actions in Selenium Protractor to automate events while performing Selenium test automation :
mouseMove () : — Performs the mouse movement on the web page.
dragAndDrop ( source , target ) : — This performs the click of the mouse at the present location i.e. the source and moves the cursor to the desired location i.e. the target without releasing the mouse. Therefore, it moves the element from source to target.
click () : — Performs the mouse click event on the web element.
click () : — Performs the mouse click event on the web element.
mouseUp () : — Performs a mouse up event on the web page.
mouseDown () : — Performs a mouse down event on the web page.
contextClick () : — This action performs a right click on any target element on the web page.
clickAndHold () : — This action performs an event of mouse click at the present location without releasing the button.
dragAndDropBy ( source, xOffset, yOffset ) : — This action performs a click and hold mouse event on the web page at the source location. It shifts the value by an offset value provided in the argument and then frees mouse actions in Selenium Protractor. Here xOffset shifts the mouse horizontally and yOffset shifts the mouse.
moveByOffset ( xOffset, yOffset ) : — This action moves the mouse from its current location or the starting location i.e. (0,0) to the specified offset. Here, xOffset is used to set the horizontal offset (negative value–move the cursor to the left) and yOffset is used to set the vertical offset (negative value–move the cursor upwards).
moveToElement ( toElement ) : — This action moves the mouse to the middle of the web element.
release () : — This function releases the pressed mouse left button at the current mouse position.
An important thing to note here is that we need to call the perform() method after making any mouse actions in Selenium Protractor on the webpage. If we don’t use perform function after calling any mouse action, then the actions will not have any effect on the web page.
Move and Hover Mouse Actions In Selenium Protractor
While performing Selenium test automation, you’d often come across test cases where you’d have to move the mouse cursor and hover over an item in the browser. This can be easily done with the mouseMove() method of mouse actions in the Selenium Protractor framework library. This helps us to get access to elements on the HTML page that get exposed only after you click on them, like the menu or the sub-items.
In the following example in this Protractor tutorial, I’ll have a look at the first action object. I’ll move the mouse cursor on the menu item through mouse actions in Selenium Protractor, and move it to the sub menu item. After this, I’ll hover on the menu that can be fetched with the id as ‘hover-menu’. This approach is also known as mouseHover().
COPY
// include all the required modules from selenium web driver and Protractor framework in this Protractor tutorial for Selenium test automation //
import { browser, element, by, ElementFinder} from 'Protractor'
// describing the test for the mouse actions demonstration //
describe(' Mouse Action Demonstration in Protractor ', function() {
// disable synchronization for non angular websites //
browser.ignoreSynchronization = true;
browser.manage().window().maximize()
// the test case which defines how to handle mouse actions in Selenium Protractor //
it(' Test to handle mouse move and hover operations in Protractor', function() {
// this is required to wait and assign implicit time value to 15 seconds
browser.manage().timeouts().implicitlyWait(15000);
browser.get("http://the-internet.herokuapp.com/hovers")
// mouse hover on a submenu
browser.actions().mouseMove(element(by.id("hover-menu"))).perform()
});
});
Did you know? The Payment Request API makes checkout flows easier, faster and consistent on shopping sites using a familiar browser-like interface.
Drag and Drop Mouse Actions In Selenium Protractor
The dragAndDrop () action of the mouse event drags the source element to the target element via mouse actions in Selenium Protractor. After this, you can perform, click or any other operation as per your requirement This action accepts two major parameters as inputs :
Source: the one which we want to pull
Target: the location where we would like to drag and drop
In the following example for this Protractor tutorial, I’ll show you how to perform the drag and drop mouse actions in Selenium Protractor
COPY
// include all the required modules from selenium web driver and Protractor framework for Protractor tutorial //
import { browser, element, by, ElementFinder} from 'Protractor'
// describing the test for the mouse actions demonstration for Selenium test automation//
describe(' Mouse Action Demonstration in Protractor ', function() {
// disable synchronization for non angular websites //
browser.ignoreSynchronization = true;
browser.manage().window().maximize()
// the test case which defines how to handle mouse actions in Protractor //
it('Test to handle drag and drop mouse operation in Protractor', function() {
// this is required to wait and assign implicit time value to 15 seconds
browser.manage().timeouts().implicitlyWait(15000);
browser.get("http://the-internet.herokuapp.com/drag_and_drop")
// perform drag and drop
browser.actions().dragAndDrop(
element(by.id("drag1")),
element(by.id("div2"))
).perform();
});
});
Click Mouse Actions In Selenium Protractor
The click() action is one of the most commonly used methods in the mouse event. Selenium click button method performs a click on the given element at a given position and then executes certain actions on the element. The location of the elements can vary depending on the size of the display on the screen.
In the following example, we execute the click action:
COPY
// include all the required modules from selenium web driver and Protractor framework for Protractor tutorial //
import { browser, element, by, ElementFinder} from 'Protractor'
// describing the test for the mouse actions in Selenium test automation demonstration //
describe(' Mouse Action Demonstration in Protractor ', function() {
// disable synchronization for non angular websites //
browser.ignoreSynchronization = true;
browser.manage().window().maximize()
// the test case which defines how to handle mouse actions in Selenium Protractor //
it(' Test to handle click mouse action in Protractor ', function() {
// this is required to wait and assign implicit time value to 15 seconds
browser.manage().timeouts().implicitlyWait(15000);
browser.get("http://the-internet.herokuapp.com/javascript_alerts")
// click the alert button
browser.actions().click(element(by.name("alert"))).perform()
});
});
Did you know? Permissions Policy enables powerful browser features for a given site using the Document Security Policy. New in this release is the ability to check if a document was served over HTTPS.
Double Click Mouse Actions In Selenium Protractor
Similar to the click method the doubleClick () method simulates a double click of the mouse. Generally, when an element is double-clicked it either activates the particular element or lifts that object from a certain point.
In the following example, we will perform a double-clicking event on the browser.
COPY
// include all the required modules from selenium web driver and Protractor framework for Protractor tutorial //
import { browser, element, by, ElementFinder} from 'Protractor'
// describing the test for the mouse action demonstration for Selenium test automation//
describe(' Mouse Action Demonstration in Protractor ', function() {
// disable synchronization for non angular websites //
browser.ignoreSynchronization = true;
browser.manage().window().maximize()
// the test case which defines how to handle mouse actions in Selenium Protractor //
it(' Test to handle double click mouse action in Protractor ', function() {
// this is required to wait and assign implicit time value to 15 seconds
browser.manage().timeouts().implicitlyWait(15000);
browser.get("http://the-internet.herokuapp.com/javascript_alerts")
// double click the double click button
browser.actions().doubleClick(element(by.id("double-click"))).perform();
});
});
Mouse Up and Mouse Down With Example
As we click up and down the button on the mouse to perform an activity. Similarly, the mouse up and mouse down methods in Protractor are used to click up and down the primary mouse button. This method is flexible and varies on the option that we configure for the primary and secondary mouse buttons in the control panel based on our choice. Suppose, if we are right-handed, we may choose the right key as primary else for left-handed we choose the primary keys as left.
In the following example, mouse up and mouse down events are executed simultaneously.
COPY
// include all the required modules from selenium web driver and Protractor framework for Protractor tutorial //
import { browser, element, by, ElementFinder} from 'Protractor'
// describing the test for the mouse action demonstration //
describe(' Mouse Action Demonstration in Protractor ', function() {
// disable synchronization for non angular websites //
browser.ignoreSynchronization = true;
browser.manage().window().maximize()
// the test case which defines how to handle mouse actions in Selenium Protractor //
it(' Test to handle mouse up and mouse down event in Protractor ', function() {
// this is required to wait and assign implicit time value to 15 seconds
browser.manage().timeouts().implicitlyWait(15000);
browser.get(" http://the-internet.herokuapp.com/drag_and_drop ")
// double click the double click button
// browser.actions().doubleClick(element(by.id("double-click"))).perform();
browser.actions().mouseDown(element(by.id("drag1")).getWebElement()).perform()
browser.actions().mouseMove(element(by.id("div2")).getWebElement()).perform()
browser.actions().mouseUp().perform()
});
});
Did you know? By setting **Pointer Events* property to “none”, hover and click events will be handled on the element, instead of any elements that are behind it. Setting this to “none” makes it possible to create drop-down menus by only ensuring that the intended elements are active and overlapping correctly.*
Keyboard Actions In Selenium Protractor
The following are a few important methods that are present in the framework and can be used to emulate keyboard actions in the browser with Protractor :
keyUp ( key ) : — This keyboard action sends a key press without releasing it. Further subsequent acts can presume that this is pressed. For example — Keys.ALT, Keys.SHIFT, or Keys.CONTROL .
keyDown ( key ) : — This function performs a key release for the above control keys that are pressed.
sendKeys ( keysTosend ) : — This function sends a series of keystrokes to the web element.
Similar to the mouse actions in Selenium Protractor, we need to call the perform() method after making any keyboard action on the webpage. If we don’t use perform() method after calling any keyboard action, then these actions will not have any effect on the web page.
Key Up, Key Down, and Send Keys With Example
The keyboard action has the Key up and Key down as the main methods that are used to trigger the API function keys in the Protractor. These approaches would be helpful if you want to hit helper keys as standard as CTRL+A, SHIFT+A, CTRL+SHIFT+Delete.
In this example for this Protractor tutorial, I’ll show this functionality by entering the character “P” value in the text bar of the web page. Later with the help of pressing the Shift key we will pass the lower case using the sendKeys function. Moreover, if you look at the bigger picture you’ll notice that all of the keyboard actions are being used together.
COPY
// include all the required modules from selenium web driver and Protractor framework for Protractor tutorial //
import { browser, element, by, ElementFinder, ProtractorBrowser, Protractor} from 'Protractor'
// describing the test for the mouse action demonstration for Selenium test automation//
describe(' Keyboard Action Demonstration in Protractor ', function() {
// disable synchronization for non angular websites //
browser.ignoreSynchronization = true;
browser.manage().window().maximize()
// the test case which defines how to handle keyboard actions in Protractor //
it(' Tests to handle keyboard actions in Protractor ', function() {
// this is required to wait and assign implicit time value to 15 seconds
browser.manage().timeouts().implicitlyWait(15000);
browser.get(" http://the-internet.herokuapp.com/key_presses ")
browser.actions()
.click(element(by.name("E")))
.keyDown(Protractor.Key.SHIFT)
.sendKeys("p")
.keyUp(Protractor.Key.SHIFT)
.perform()
});
});
Mouse Actions In Selenium Protractor on Cloud Selenium Grid
We can run the same Selenium test automation script for handling mouse behavior on a cloud Selenium grid platform. It gives us the opportunity to run tests across 2000+ real-time browsers and devices in parallel. You only need to make a few changes in the tet script, i.e. to create a driver to connect to the LambdaTest hub. Below is the revised script with the requisite modifications.
COPY
// test_config.js //
// The test_config.js file serves as a configuration file for our test case for Protractor tutorial //
LT_USERNAME = process.env.LT_USERNAME || "irohitgoyal"; // Lambda Test User name
LT_ACCESS_KEY = process.env.LT_ACCESS_KEY || "r9JhziRaOvd5T4KCJ9ac4fPXEVYlOTealBrADuhdkhbiqVGdBg"; // Lambda Test Access key
exports.capabilities = {
'build': ' Automation Selenium Webdriver Test Script ', // Build Name to be display in the test logs
'name': ' Protractor Selenium Frame Test on Chrome', // The name of the test to distinguish amongst test cases //
'platform':'Windows 10', // Name of the Operating System
'browserName': 'chrome', // Name of the browser
'version': '79.0', // browser version to be used
'console':false, // flag to check whether to capture console logs.
'tunnel': false // flag to check if it is required to run the localhost through the tunnel
'visual': false, // flag to check whether to take step by step screenshot
'network':false, // flag to check whether to capture network logs
};
// setting required config parameters //
exports.config = {
directConnect: true,
// Desired Capabilities that are passed as an argument to the web driver instance.
capabilities: {
'browserName': 'chrome' // name of the browser used to test //
},
// Flavour of the framework to be used for our test case //
framework: 'jasmine',
// The patterns which are relative to the current working directory when
Protractor methods are invoked //
specs: ['test_frame.js'],
// overriding default value of allScriptsTimeout parameter //
allScriptsTimeout: 10000,
jasmineNodeOpts: {
// overriding default value of defaultTimeoutInterval parameter //
defaultTimeoutInterval: 10000
},
onPrepare: function () {
browser.manage().window().maximize();
browser.manage().timeouts().implicitlyWait(10000);
}
};
Test Script : –
COPY
// include all the required modules from selenium web driver and Protractor framework for Protractor tutorial //
import { browser, element, by, ElementFinder} from 'Protractor'
var script = require (‘Protractor’) ;
var webdriver = require (‘selenium-webdriver’) ;
// Building the web driver that we will be using in Lambda Test
var buildDriver = function(caps) {
return new webdriver.Builder()
.usingServer(
"http://" +
LT_USERNAME +
":" +
LT_ACCESS_KEY +
"@hub.lambdatest.com/wd/hub"
)
.withCapabilities(caps)
.build();
};
// describing the test for the mouse action demonstration //
describe(' Mouse Action Demonstration in Protractor ', function() {
// adding the before each event that builds the driver and triggers before the execution of the test script.
beforeEach(function(done) {
caps.name = this.currentTest.title;
driver = buildDriver(caps);
done();
});
// disable synchronization for non angular websites //
browser.ignoreSynchronization = true;
browser.manage().window().maximize()
// the test case which defines how to handle mouse actions in Selenium Protractor //
it(' Test to handle mouse up and mouse down event in Protractor ', function() {
// this is required to wait and assign implicit time value to 15 seconds
browser.manage().timeouts().implicitlyWait(15000);
browser.get(" http://the-internet.herokuapp.com/drag_and_drop ")
// double click the double click button
// browser.actions().doubleClick(element(by.id("double-click"))).perform();
browser.actions().mouseDown(element(by.id("drag1")).getWebElement()).perform()
browser.actions().mouseMove(element(by.id("div2")).getWebElement()).perform()
browser.actions().mouseUp().perform()
});
});
As seen above, by including a few lines of code, you can connect to the LambdaTest Platform and execute our regular test script in the cloud. In order to have this configured, you need to create the desired capability matrix.
You can visit LambdaTest Selenium desired capabilities generator for generating the appropriate configuration, using this you can determine the environment in which you will conduct the tests. Moreover, you only need to pass our LambdaTest username and access key to the config file that will securely recognize us on the LambdaTest platform.
All In All
With this comes the end of this Protractor tutorial! To summarize, I’ve explored how you can simulate mouse and keyboard behavior in a browser using various functions in the Selenium Protractor framework. With Selenium Protractor, you also get the flexibility to combine mouse and keyboard actions for automated browser testing. After executing the functions, perform() is used to execute the actions.
This is the end! Or at least the end of the beginning, we’ve covered quite a few topics on Selenium Protractor now, I’d like you to go ahead and read them. Also, do click on the bell icon for any future notifications on new blogs and tutorials. Do share this article with your friends looking for the answers on handling mouse actions and keyboard events, a retweet or a social is always welcome. Happy Testing!!!😊
Top comments (0)