How to test if an element has class using Protractor?


We will learn to use the protractor test if an element has class using Protractor. Protractor is an end-to-end testing framework for Angular and AngularJS applications. Protractor is built on top of WebDriverJS, a JavaScript implementation of the WebDriver API, and supports multiple browsers such as Chrome, Firefox, and Safari.

Testing if an element has a specific class is important because it allows us to check if a certain style or behaviour is applied to the element as intended. This is especially useful in scenarios where the presence or absence of a specific class triggers certain styles or behaviours. By knowing how to test for the presence of a class using Protractor, we can write more effective and efficient tests that help ensure the quality of our web applications.

We will take two different examples to show the use of a protractor to test if an element has class.

  • Test if an element has a specific class

  • Test if a product is sold out using the class attribute

Test if an Element has Specific Class

We can check if an element has a class containing a certain string using protractor.

Syntax

Users can follow the below syntax to use the protractor to test whether an element has class containing a particular string or not.

/* Check that the 'class' attribute of the element contains a certain string */
expect(element(by.css('your css selector') )
.getAttribute('class'))
.toContain('your string');

It will pass the test if a class contains the given string, else it will fail the test.

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 a <div> element with an id of "myDiv". The <div> element has two classes: "Web" and "page".

<html>
<head>
</head>
<body>
   <h2>Test if an element has specific class </h2>
   <div id = "myDiv" class = "Web page"> </div>
</body>
</html>

test.js

This test.js file tests whether a specific element with ID 'myDiv' on a webpage contains the string 'Web' in its class attribute. Additionally, it disables AngularJS synchronization before loading the webpage to ensure that any non-Angular elements on the page can be properly tested.

describe('Test Page', function() {
   it(' should contain string "Web" in class ', function() {

      // Disable AngularJS synchronization 
      browser.waitForAngularEnabled(false);
            
      // Load the webpage 
      browser.get('../tests/test.html');

      // Find the element with ID 'myDiv' 
      let myDiv = element(by.id('myDiv'));

      /* Check that the 'class' attribute of the element contains the string 'Web' */
      expect(myDiv.getAttribute('class')).toContain('Web');
   });
});

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.

Test if a Product is sold out Using Class Attribute

Let's say you have a webpage that displays different types of products, and you want to test if a specific product has been marked as "sold out" by checking if it has a "sold-out" class on its element. You can use Protractor to automate this testing process.

Example

This is an example of using Protractor to test if a product element with a particular data-id has class sold-out. It passes the test if it is found that the product is out of the stock, else test fails.

test.html

This HTML page contains two products, Mango juice and Orange juice. The Mango juice product has a "sold-out" class on its "Out of stock" span element, while the Orange juice product is in stock and does not have a "sold-out" class.

<html>
<head>
   <meta charset = "UTF-8">
</head>
<body>
   <h2>Test if particular product has class sold-out</h2>
   <div class = "product" data-id = "123">
      <h3> Mango juice </h3>
      <p> It is made of fresh Mangoes </p>
      <span class = "price" > Rs. 20\- </span>
      <span class = "sold-out" > Out of stock </span>
   </div>
   <div class = "product" data-id = "45">
      <h3> Orange juice </h3>
      <p> It is made of fresh Oranges </p>
      <span class = "price" > Rs. 15\- </span>
   </div>
</body>
</html>

test.js

This test file tests whether a product with a certain ID has the class 'sold-out' if it is out of stock. It does so by loading a webpage containing product information, finding the product element with the specified data ID, waiting for it to be visible, waiting for 1 second, finding the element with class 'sold-out' inside the product element, and then checking whether its 'class' attribute contains the string 'sold-out'. If it does, the test passes, and if it doesn't, the test fails.

describe('Product page', function() {
   it('should display sold-out message for out of stock product' , function() {
      browser.waitForAngularEnabled(false);

      browser.get('../tests/hasClass2.html');

      // Find the product element with data-id="123"
      var product = element(by.css('.product[data-id="123"]'));

      // Wait for the product element to be visible
      browser.wait(ExpectedConditions.visibilityOf(product), 5000);

      // Wait for 1 second before checking for the class
      browser.sleep(1000);

      /* Find the element with class 'sold-out' inside the product element */
      product.element(by.className('sold-out')).getAttribute('class').then(function(className) {
         /* Check that the 'class' attribute of the element contains the string 'sold-out' */
         expect(className).toContain('sold-out');
      } );
   } );
} );

Output

We have demonstrated two examples of using a Protractor to test if an element has class. One is a simple example, and another example shows how testing for presence of a class can be useful.

Updated on: 06-Apr-2023

426 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements