如何使用protractor检查元素中是否存在文本内容

如何使用protractor检查元素中是否存在文本内容

Protractor是一个为AngularJS应用程序开发的端到端测试框架,但也适用于非Angular JS应用程序。它以真实用户的方式与应用程序进行交互,并在真实浏览器中运行测试。在本文中,我们将使用Protractor来检查我们如何等待元素中的文本内容出现。

先决条件:安装和设置Protractor

方法: 我们将创建一个基本的测试程序,用于检查元素中是否存在文本内容。所有的Protractor测试都会有一个文件,该文件包含了配置,并且是初始化测试的初始文件。

以下是上述方法的逐步实施。

步骤1: 我们首先要创建一个 conf.js 文件,其中包含与Protractor一起使用的配置。

conf.js

exports.config = { 
  
 // Define the capabilities to be passed 
 // to the webdriver instance 
 capabilities: { 
   browserName: "chrome", 
 }, 
  
 // Define the framework to be use 
 framework: "jasmine", 
   
 // Define the Spec patterns. This is relative 
 // to the current working directory when 
 // protractor is called 
 specs: ["test.js"], 
  
 SELENIUM_PROMISE_MANAGER: false, 
  
 // Define the options to be used with Jasmine 
 jasmineNodeOpts: { 
  defaultTimeoutInterval: 30000, 
 }, 
  
 // Define the baseUrl for the file 
 baseUrl: "file://" + __dirname + "/", 
  
 onPrepare: function () { 
  browser.resetUrl = "file://"; 
 }, 
};

步骤2: 我们将创建一个名为 test.html 的HTML文件,其中包含要测试的元素。

test.html

<!DOCTYPE html> 
<html> 
<head> 
    <title> 
      fade-in effect on page load using JavaScript 
    </title> 
    <script type="text/javascript"> 
        var opacity = 0; 
        var intervalID = 0; 
        window.onload = fadeIn; 
    
        function fadeIn() { 
            setInterval(show, 200); 
        } 
    
        function show() { 
            var body = document.getElementById("fade-in"); 
            opacity = Number(window.getComputedStyle(body) 
                             .getPropertyValue("opacity")); 
            if (opacity < 1) { 
                opacity = opacity + 0.1; 
                body.style.opacity = opacity 
            } else { 
                clearInterval(intervalID); 
            } 
        } 
    </script> 
</head> 
<body> 
  <!-- The element to be tested -->
  <div id="fade-in" 
       style="opacity: 0;"> 
    GFG 
  </div> 
</body> 
</html>

步骤3: 我们将创建 test.js 文件。在这个文件中,我们将访问上面的HTML文件,然后等待元素具有特定的文本内容。浏览器是由Protractor创建的全局对象,用于浏览器级别的命令,例如使用browser.get()方法进行导航。描述和语法来自Jasmine框架,其中describe是你的测试的描述,它定义了测试的步骤。

test.js

describe('Protractor Demo App', function () { 
  it('should have a title', async function () { 
      
      var EC = protractor.ExpectedConditions; 
  
      // Disable waiting for Angular render update 
      browser.waitForAngularEnabled(false) 
  
      // Get the HTML file that has to be tested 
      browser.get('test.html'); 
  
      // Get the fade in element 
      let fadeIn = element(by.id('fade-in')); 
  
      // Waits for the element with id 'myInput' to contain the input 'foo'. 
      browser.wait(EC.textToBePresentInElementValue(fadeIn, 'GFG'), 5000); 
  
      expect(fadeIn.getText()).toEqual('GFG'); 
  }); 
});

步骤 4:

最后,我们将使用下面的命令来运行配置文件。这将运行配置文件,并且测试将按照下面的输出进行运行。

protractor conf.js

输出:

如何使用protractor检查元素中是否存在文本内容

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程