Open In App

How to get x and y coordinates of an element in protractor Node.js ?

Improve
Improve
Like Article
Like
Save
Share
Report

Protractor is an end-to-end test framework that is developed for AngularJS and Angular applications. It basically runs the tests against the application which is interacting with it as a real user would, running in a real browser. In the following example, we are going to get the x and y coordinates of an element and check if it is as expected or not.

Pre-requisite: Installation and Setup of Protractor

Approach:

  • We are going to create a basic test program in which we are going to check whether the x and y coordinates of an element is as expected or not.
  • All the Protractor tests will have a file containing the configuration and this file will be the initial file that will initiate the test.
  • Let’s create this file with the name conf.js.

Example: Filename: conf.js

Javascript




exports.config = {
  
    // Capabilities values for
    // webdriver instance
    capabilities: {
        'browserName': 'chrome'
    },
  
    // Framework value
    framework: 'jasmine',
  
    // The Spec patterns are relative to the 
    // current working directory when
    // protractor is called.
    specs: ['test.js'],
  
    // Options which are passed to our
    // framework ie. Jasmine.
    jasmineNodeOpts: {
        defaultTimeoutInterval: 30000
    },
  
    // File URL
    baseUrl: 'file://' + __dirname + '/',
  
    onPrepare: function () {
        browser.resetUrl = 'file://';
    }
};


Now let’s create our HTML file called test.html which will contain the element to be tested.

Filename: test.html

HTML




<!DOCTYPE html>
<html lang="en">
<body>
    <!-- The element to be tested -->
    <div id="foo" style="position: absolute;
        top:20px; left: 15px">
        Inner text
    </div>
</body>
</html>


Now let’s create our test file test.js. In this file, we are going to access an HTML file and then get the x and y coordinates and will check if it is as set in the HTML file or not. Browser is a global created by Protractor.

Jasmine framework provides the describe() function and it() function where the describe is a description of your test while it is the steps for the test.

Filename: test.js

Javascript




describe('Protractor Demo App', function () {
    it('should have a title', function () {
        // Disabling waiting for angular
        browser.waitForAngularEnabled(false)
  
        // Get our html file for testing
        browser.get('test.html');
  
        // Test if the element have required coordinates
        let foo = element(by.id('foo'));
        expect(foo.getLocation()).toEqual(
        jasmine.objectContaining({
            x: 15,
            y: 20
        }));
    });
});


Run the conf.js file using the following command:

protractor conf.js

Output:



Last Updated : 12 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads