WebdriverIO - Class Name Locator



Once we navigate to a webpage, we have to interact with the webelements available on the page like clicking a link/button, entering text within an edit box, and so on to complete our automation test case.

For this, our first job is to identify the element. We can use the class name attribute for an element for its identification. It is a very useful locator and speeds up the execution of automation tests in comparison to xpath.

In the WebdriverIO code, we have the option to specify the value of the class name attribute of an element in the below format −

$('=.value of class attribute')

Or, we can store this expression in a variable as follows −

const p = $('=.value of class attribute')

Let us identify the text highlighted in the below image and obtain its text −

Comparison to Xpath

The element highlighted in the above image has the class attribute value as heading.

The Code Implementation is as follows

// test suite name
describe('Tutorialspoint application', function(){
   //test case
   it('Identify element with Class Name', function(){        
      // launch url
      browser.url('https://www.tutorialspoint.com/about/about_careers.htm')
      //identify element with Class Name then obtain text
      console.log($(".heading").getText() + " - is the text.")
   });
});

Run the Configuration file - wdio.conf.js file with the following command −

npx wdio run wdio.conf.js

The details on how to create a Configuration file are discussed in detail in the Chapter titled Wdio.conf.js file and Chapter titled Configuration File generation. The following screen will appear on your computer −

Code Implementation

After the command has been executed successfully, the text of the element - About Tutorialspoint is printed in the console.

Advertisements