How to use protractor to check whether text is present in an element or not?


We will learn to use Protractor to check whether text is present in an element or not. Protractor is an end-to-end testing framework for Angular and AngularJS applications. It uses WebDriverJS and runs tests written in Jasmine or Mocha, allowing for automated browser testing of web applications. Protractor can simulate user interaction with the application, test for expected behaviour, and report on test results. It also includes several features designed specifically for Angular, such as the ability to wait for Angular-specific elements to load before executing tests.

Note − To use a protractor, ensure that the protractor installation and setup 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 whether the text is present in an element or not.

  • Text in button

  • Text in fading-in element

Text in Button

Using a protractor, we can check whether any text content is present or not in a button.

Syntax

Users can follow the below syntax to check whether text is present in element or not.

// Wait for the button to be present
browser.wait(EC.presenceOf(button), 5000);
// Check if the text content is as expected
expect(button.getText()).toEqual('Click me');

It will wait for the button to be present and then will check if the text is present in a button.

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 button with the text “Click me”.

<html>
<head>
</head>
<body>
   <h2>Check whether text is present in button</h2>
   <button id = "myButton" > Click me </button>
</body>
</html>

test.js

The test.js file checks whether a button with a specific text is present on a web page or not. We disable waiting for Angular render update as it may not be an Angular application. Then we check if the button has the text "Click me" using the button.getText( ) method and compare it with the expected value using the expect() method.

describe('Protractor Demo App', function() {
   it( 'should have a button with specific text' , async function() {

      // Disable waiting for Angular render update
      browser.waitForAngularEnabled( false );
        
      // Get the HTML file that has to be tested
      browser.get('../tests/test.html');
        
      let EC = protractor.ExpectedConditions;

      // Wait for the button to be present
      let button = element(by.buttonText( 'Click me' ));
      browser.wait(EC.presenceOf(button), 5000);
        
      // Verify the button text
      expect(button.getText()).toEqual( 'Click me' );
   });
});

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.

Text in Fading-in Element

When we have an element that fades in using the CSS transition property. Using a protractor, we can check whether text is present in that element.

Example

We have taken another example. conf.js file will be the same. The test script waits for a specific HTML element with the ID "fade-in" to become visible, retrieves its text content, and checks if it matches the expected text. The HTML file includes CSS styling and a JavaScript function that fades in the text of the element over some time.

test.html

The HTML file has a hidden text element that fades in when the page loads using JavaScript.

<html>
<head>
   <style>
      #fade-in {
         opacity: 0;
         transition: opacity 0.5s ease-in-out;
      }
   </style>
   <script type="text/javascript">
      let opacity = 0;
      let intervalID = 0;
      window.onload = fadeIn;
          
      function fadeIn() {
         setInterval(show, 200);
      }
          
      function show() {
         let element = document.getElementById("fade-in");
         opacity = Number(window.getComputedStyle(element)
         .getPropertyValue("opacity"));
         if (opacity < 1) {
            opacity = opacity + 0.1;
            element.style.opacity = opacity
         } else {
            clearInterval(intervalID);
         }
      }
   </script>
</head>
<body>
   <h2>Check whether text is present in an element</h2>
   <p id = "fade-in" > This text fades in </p>
</body>
</html>

test.js

It is our test.js file. It waits for the element to become visible, retrieves its text content, and checks if it matches the expected text 'This text fades in'. It also disables waiting for Angular render update and navigates to the HTML file that has to be tested.

describe('Protractor Demo App', function() {
  
   it('should have faded in', function() {
      // Disable waiting for Angular render update
      browser.waitForAngularEnabled(false);
        
      // Navigate to the HTML file that has to be tested
      browser.get('../tests/test.html');
        
      // Get the element that fades in
      let fadeInElement = element(by.id('fade-in'));
        
      // Wait for the element to become visible
      browser.wait(function() {
         return fadeInElement.isDisplayed().then(function(isDisplayed) {
            return isDisplayed;
         });
      }, 5000);
        
      // Get the text content of the fading-in element
      let fadeInText = fadeInElement.getText();
        
      // Check if the text content is as expected
      expect(fadeInText).toEqual('This text fades in');
   });
});

Output

We have learned to check whether any text content is present or not in an element. In the first example, we checked for the text present in a button. And then, in another example, we took a text in the fading-in element. In both cases, we could check text availability in those elements.

Updated on: 06-Apr-2023

257 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements