Watir - 自動等待



在本章中,讓我們詳細瞭解等待。為了瞭解自動等待,我們建立了一個簡單的測試頁面。當用戶在文字框中輸入文字時,將觸發 onchange 事件,並且在 3 秒後啟用按鈕。

Watir 具有一個 wait_unit api 呼叫,用於等待特定事件或屬性。我們將針對以下給出的測試頁面對其進行測試:

語法

browser.button(id: 'btnsubmit').wait_until(&:enabled?)
//here the wait is on the button with id : btnsubmit to be enabled.

testwait.html

<html>
   <head>
      <title>Testing UI using Watir</title>
   </head>
   
   <body>
      <script type = "text/javascript">
         function wsentered() {
            setTimeout(function() {
            document.getElementById("btnsubmit").disabled = false; }, 3000);
         }
         function wsformsubmitted() {
            document.getElementById("showmessage").style.display = "";
         }
      </script>
      
      <div id = "divfirstname">
         Enter First Name : 
         <input type = "text" id = "firstname" name = "firstname" onchange = "wsentered()" />
      </div>
      <br/>
      <br/>
      <button id = "btnsubmit" disabled onclick = "wsformsubmitted();">Submit</button>
      <br/<
      <br/<
      
      <div id = "showmessage" style = "display:none;color:green;font-size:25px;">l;
         Button is clicked
      </div>
   </body>
</html>

輸出

Automatic Waits

在文字框中輸入文字時,你必須等待 3 秒才能啟用按鈕。

Automatic Waits

單擊“提交”按鈕時,將顯示以下文字:-

Submit Button

現在,由於我們為啟用按鈕添加了延遲,因此自動化難以處理此類情況。每當我們遇到延遲或必須等待某些元素的事件或屬性才能定位時,我們可以使用 wait_until,如下所示:-

使用 wait_until 的 Watir 程式碼

require 'watir'
b = Watir::Browser.new :chrome
b.goto('https:///uitesting/testwait.html')
t = b.text_field(name: 'firstname')
t.exists?
t.set 'Riya Kapoor'
b.screenshot.save 'waittestbefore.png'
t.value
t.fire_event('onchange')
btn = b.button(id: 'btnsubmit').wait_until(&:enabled?)
btn.fire_event('onclick');
b.screenshot.save 'waittestafter.png'

接下來,使用以下命令

btn = b.button(id: 'btnsubmit').wait_until(&:enabled?)

Watir 將等待按鈕啟用,然後進行單擊事件的觸發。捕獲的螢幕截圖如下:

Waittestbefore.png

Waittestbefore

waittestafter.png

waittestafter
廣告