如何使用 Protractor 檢查文字是否存在於元素中?


我們將學習如何使用 Protractor 檢查文字是否存在於元素中。Protractor 是一個用於 Angular 和 AngularJS 應用程式的端到端測試框架。它使用 WebDriverJS 並執行用 Jasmine 或 Mocha 編寫的測試,從而可以對 Web 應用程式進行自動化瀏覽器測試。Protractor 可以模擬使用者與應用程式的互動,測試預期的行為並報告測試結果。它還包含一些專為 Angular 設計的功能,例如能夠在執行測試之前等待 Angular 特定元素載入。

注意 - 要使用 Protractor,請確保已完成 Protractor 的安裝和設定。使用者可能需要將執行策略設定為“RemoteSigned”

或者如果在不執行此操作的情況下無法工作,則設定為“Unrestricted”。

命令

Set-ExecutionPolicy RemoteSigned
Or
Set-ExecutionPolicy Unrestricted

我們將看到兩種不同的場景來檢查文字是否存在於元素中。

  • 按鈕中的文字

  • 淡入元素中的文字

按鈕中的文字

使用 Protractor,我們可以檢查按鈕中是否存在任何文字內容。

語法

使用者可以按照以下語法來檢查文字是否存在於元素中。

// 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');

它將等待按鈕出現,然後檢查按鈕中是否存在文字。

示例

在以下示例中,我們建立了 3 個檔案 - conf.js、test.html 和 test.js。

我們在 conf 資料夾中有一個 conf.js 檔案,tests 資料夾包含 test.html 和 test.js。

conf.js

此檔案是 Protractor 的配置檔案。它將瀏覽器功能設定為 Chrome,指定 Jasmine 框架,並指定測試指令碼檔案的位置。它還設定了預設超時間隔和測試的基本 URL。onPrepare 函式用於設定瀏覽器的重置 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

此檔案包含一個帶有“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

test.js 檔案檢查網頁上是否存在帶有特定文字的按鈕。我們停用等待 Angular 渲染更新,因為它可能不是 Angular 應用程式。然後我們使用 button.getText() 方法檢查按鈕是否包含文字“Click me”,並使用 expect() 方法將其與預期值進行比較。

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' );
   });
});

執行配置檔案的命令

protractor conf.js(file path)

輸出

我們可以看到所有測試都通過了,並且沒有錯誤。

淡入元素中的文字

當我們有一個使用 CSS transition 屬性淡入的元素時。使用 Protractor,我們可以檢查該元素中是否存在文字。

示例

我們採取了另一個示例。conf.js 檔案將保持不變。測試指令碼等待具有 ID“fade-in”的特定 HTML 元素可見,檢索其文字內容,並檢查它是否與預期文字匹配。HTML 檔案包含 CSS 樣式和一個 JavaScript 函式,該函式在一段時間內淡入元素的文字。

test.html

HTML 檔案包含一個隱藏的文字元素,該元素在頁面載入時使用 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

這是我們的 test.js 檔案。它等待元素可見,檢索其文字內容,並檢查它是否與預期文字“This text fades in”匹配。它還停用等待 Angular 渲染更新並導航到要測試的 HTML 檔案。

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');
   });
});

輸出

我們已經學習瞭如何檢查元素中是否存在任何文字內容。在第一個示例中,我們檢查了按鈕中是否存在文字。然後,在另一個示例中,我們在淡入元素中獲取了文字。在這兩種情況下,我們都可以檢查這些元素中文字的可用性。

更新於: 2023年4月6日

398 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告