How to use protractor to check if an element is visible?


We will learn to use Protractor to check if an element is visible. Protractor is an end-to-end testing framework for Angular and AngularJS applications. It uses Selenium WebDriver to automate browser interactions and provides a high-level API to write tests in JavaScript or TypeScript. It uses Jasmine as the test framework. It provides many features, such as automatic synchronization with the AngularJS application, page object model support, and more.

Note − To use a protractor, make sure that installation and setup of the protractor have already been done. User may need to set the Execution Policy to ‘RemoteSigned’

Or ‘Unrestricted’ if it does not work without doing it.

Command

Set-ExecutionPolicy RemoteSigned
Or
Set-ExecutionPolicy Unrestricted

We will see two different scenarios to check if an element is visible.

  • Check if the element is present and visible

  • Wait for the element to be visible

Check if Element is Present and Visible

The methods isPresent( ) and isDisplayed( ) are used to check the visibility of a web element in Protractor. Method isPresent( ) returns a boolean value of true if element is present in the DOM, regardless of its visibility, else it returns false. Method isDisplayed( ) returns a boolean value of true if element is present in the DOM and visible on the page, else it returns false.

Syntax

Users can follow the below syntax to check if an element is present and visible.

// Check if present
expect(myElement.isPresent()).toBe(true);
// check if visible
expect(myElement.isDisplayed()).toBe(true);

It will check the presence and visibility of an element on a page.

Example

In the below example, we have created 3 files – conf.js, test.html and test.js.

We have a conf.js file in a folder conf, and the tests folder contains test.html and test.js.

conf.js

This file is the configuration file for Protractor. It sets the browser capabilities to Chrome, specifies the Jasmine framework, and specifies the location of the test script file. It also sets a default timeout interval and the base URL for the tests. The onPrepare function is used to set the browser's reset URL.

exports.config = {
   directConnect: true,

   // Capabilities to be passed to the webdriver instance.
   capabilities: {
      'browserName': 'chrome'
   },

   // Framework to use. Jasmine is recommended.
   framework: 'jasmine',

   /* Spec patterns are relative to the current working directory when protractor is called */
   specs: ['../tests/test.js'],

   // Options to be passed to Jasmine.
   jasmineNodeOpts: {
      defaultTimeoutInterval: 30000
   },
   // Define the baseUrl for the file
   baseUrl: "file://" + __dirname + "/",
     
   onPrepare: function () {
      browser.resetUrl = "file://";
   }
};

test.html

This file contains elements to be tested.

<html>
<head>
</head>
<body>
   <h2>Check if element is present and visible using Protractor</h2>
   <p>This is an example page.</p>
   <div id = "my-element" >
      <p>This is the element to check.</p>
   </div> 
</body>
</html>

test.js

The test.js file is used to define the tests that Protractor will run. It contains test cases, which are composed of describe, and it blocks. The describe block defines the name of the test suite, and the it block defines a specific test case. Within the it block, test logic is defined using Protractor's API. Each it block is executed sequentially, and Protractor reports the results of each test case. Here is our test.js file.

describe('Example Test Suite', function() {
   it('should check if an element is present and visible', function() {

      browser.waitForAngularEnabled(false)

      // Load the webpage
      browser.get('../tests/test.html');
        
      // Find the element to check
      let myElement = element(by.css('#my-element'));

      // Check if the element is present and visible
      
      // Check that the element is present on the page
      expect(myElement.isPresent()).toBe(true); 

      // Check that the element is visible on the page
      expect(myElement.isDisplayed()).toBe(true); 

   }) ;
}) ;

Command to run configuration file

protractor conf.js(file path)

Output

We can see that we are getting all tests passed, and there is no error.

Wait for Element to be Visible

We will wait for an element to become visible before checking it using the browser.wait. By using this function, we can ensure that the test script waits for the element to become visible before attempting to interact with it. This helps to prevent errors and ensures that the test is more reliable.

Example

We have taken another example. conf..js file will be the same. Custom function waitForElementToBeVisible( ) uses the ExpectedConditions object of Protractor to define the condition for the wait. In this case, the condition is visibilityOf, which means that the function will wait until the element is visible on the page. The browser.wait method is used to wait for the condition to be met, and the function returns a promise that is resolved when the element becomes visible.

test.html

This HTML file contains the button and hidden elements.

<html>
<head>
</head>
<body>
   <h2>Wait for element to be visible and then check</h2>
   <button onclick = "document.getElementById('hiddenElement').style.display = 'block'"> Show Element </button>
   <div id = "hiddenElement" style = "display: none"> This is a hidden element </div>
</body>
</html>

test.js

This code tests whether an element is visible or not on a webpage. It first disables Angular waiting, then loads the webpage and waits for a button with the text "Show Element" to become visible. The waitForElementToBeVisible function waits for the element to become visible using the ExpectedConditions object and returns a promise.

describe('Test Suite', function() {
   it('should check if an element is visible', function() {
      browser.waitForAngularEnabled(false)

      // Load the webpage
      browser.get('../tests/test.html');
            
      // Wait for the button to become visible
      waitForElementToBeVisible(by.buttonText('Show Element')).then(function() {
      
         // Click the button to show the element
         element(by.buttonText('Show Element')).click();
           
         // Wait for the element to become visible
         waitForElementToBeVisible(by.id('hiddenElement')).then(function() {
         
            // Expect the element to be visible
            expect(element(by.id('hiddenElement')).isDisplayed()).toBeTruthy();
         }) ;
      }) ;
   }) ;
}) ;
  
// Function to wait for an element to become visible
function waitForElementToBeVisible(elementFinder) {
   let EC = protractor.ExpectedConditions;
   return browser.wait(EC.visibilityOf(element(elementFinder)), 5000);
}

Output

We have learned to check if an element is visible using Protractor using two methods, isPresent( ) and isDisplayed( ). We have also seen syntax and examples to check if an element is present and visible or wait for an element to become visible before checking it. Users can use any method according to their requirements.

Updated on: 06-Apr-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements