How to use protractor to wait for the element’s attribute to change to a particular value?


We will learn to use protractor to wait for the element’s attribute to change to a particular value. Protractor is an end-to-end testing framework for Angular and AngularJS applications. Protractor has built-in support for waiting for Angular-specific elements to load and be ready before performing test operations.

We need to learn this topic to ensure that tests only proceed when specific elements are ready, avoiding errors and improving the accuracy of the test results. Waiting for an attribute to change to a particular value also helps identify and debug issues related to data manipulation and other dynamic events on the webpage.

We will take two different examples to show the use of protractor to wait for the element’s attribute to change to a particular value.

  • Change on a click of the button

  • Change after the given time

Change on a Click of the Button

We will wait for the element’s attribute to change to a particular value when we click a button.

Syntax

Users can follow the below syntax to use the protractor to wait to value get changed to the expected value.

browser.wait(function() {
   return element(by.css('your-css-selector'))
   .getAttribute( 'attribute-name' )
   .then(function (value) {
      return value === 'expected-value';
   } ) ;
}, timeout-in-milliseconds) ;

It will wait for an element with a specified CSS selector to have a specified attribute value with a specified timeout.

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, and 'chromeOptions' with 'args' sets the logging level to '3', the least verbose level, in the Chrome browser launched by Protractor, 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',
      'chromeOptions' : {
         args: ['--log-level=3']
      }
   } ,

   // 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 a div element and a button that changes the div's attribute value and text content.

<html>
<head>
</head>
<body>
   <h2>Wait for attribute to change to particular value</h2>
   <div id = "myElement" data-state = "initial" > Initial State </div>
   <button id = "change-state" onclick = "changeState()" > Change State </button>
   <script>
      function changeState() {
         let myElement = document.getElementById('myElement');
         myElement.setAttribute('data-state', 'changed');
         myElement.textContent = 'Changed State';
      }
   </script>
</body>
</html>

test.js

The test.js file is an example of using Protractor to wait for an element's attribute to change to a particular value. It disables the waiting for Angular render update, loads a page with an element whose attribute is changed on a button click, and waits for the attribute to change to the expected value using the browser.wait() function, and then verifies that the element's text content has changed.

describe('Protractor Attribute Wait Example 1' , function() {
   it('should wait for an element attribute to change' , function() {
      // Disable waiting for Angular render update
      browser.waitForAngularEnabled(false);
            
      browser.get('../tests/test.html');
        
      let myElement = element(by.id('myElement'));
        
      /* Wait for the data-state attribute to change to 'changed' */
      browser.wait(function() {
         return myElement.getAttribute('data-state')
         .then(function(state) {
            return state === 'changed';
         });
      }, 5000);
        
      // Verify that the element's text content has changed
      expect(myElement.getText()).toEqual( 'Changed State' );
   });
});

Command to run configuration file

protractor conf.js(file path)

Output

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

Change After the Given time

Value will be changed in HTML after a given time interval. We will use a protractor to wait for that value to be changed.

Example

This is an example of using a Protractor to wait for an element's attribute to change to a particular value within a given time. It includes an HTML file that uses jQuery to change the value of a div element's attribute and a test file that verifies the change using the browser.wait() function and the expect() assertion. conf.js file will be the same.

test.html

This HTML file uses the jQuery library to change the value of a div element's data-status attribute and text content after 3 seconds of page load.

<html>
<head>
   <script src = "https://code.jquery.com/jquery-3.6.0.min.js" > </script>
</head>
<body>
   <h2>Wait for attribute to change to particular value in given time</h2>
   <div id = "my-div" data-status = "initial" > Initial Status </div>
   <script>
      $(document).ready(function() {
         setTimeout(function() {
            $('#my-div').attr('data-status', 'updated').text('Updated Status');
         }, 3000);
      });
   </script>
</body>
</html>

test.js

It is our test.js file that verifies that an element's attribute changes to a particular value after waiting for it. The browser.wait() function is used to wait for the div's data-status attribute to equal 'updated' within a 5000 millisecond timeout. Finally, the test asserts that the attribute has been updated to the expected value using expect().

describe('Protractor Attribute Wait Example 2', function() {
   beforeEach(function() {
      browser.waitForAngularEnabled(false);
            
      browser.get('../tests/test.html');
   });

   it('should wait for the element attribute to change to a particular value', function() {
      // Get the div element
      let divElement = $('#my-div');

      /* Wait for the div's data-status attribute to equal 'updated' */
      browser.wait(function() {
         return divElement.getAttribute('data-status').then(function(status) {
            return status === 'updated';
         } ) ;
      }, 5000);

      // Verify that the attribute has been updated
      expect(divElement.getAttribute('data-status')).toBe('updated');
   } ) ;
} ) ;

Output

We have demonstrated two different examples of using a Protractor to wait for the element's attribute to change to a particular value, including waiting for an attribute to change on a button click and waiting for an attribute to change after a given time interval. It is an essential skill for ensuring the accuracy and reliability of your end-to-end tests.

Updated on: 06-Apr-2023

362 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements