2015-09-01 62 views
0

我試圖創建一個函數,我可以調用任何測試,將看看被傳遞的元素(鏈接文本,Css選擇器,Xpath,ID),點擊元素,然後驗證出現的URL加載後。我遇到的問題是它在函數完成之前返回。如何在返回前等待函數完成?

我知道我需要實現異步和回調,但我很難理解結構。

clickIDverifyURL: function clickByID (elementVar, elementURL){ 
     var rem = this.remote; 

     // if statements to look at elementVar and select the right one.. example: 
     // rem.setFindByTimeout(10000) 
     // .findByXpath (elementVar) 
     // .click() 
     // .end() 

     return this.remote 
      // if I code it right, I shouldn't need this sleep right? 
      .sleep(30000) 
      .getCurrentUrl() 
      .then(function(currURL) { 
       console.log(currURL); 
       try { 
        assert.strictEqual(currURL, elementURL, "This test checks to see if the current URL is correct.") 
       } 
       catch (e) 
       { 
        console.log(e) 
       } 
      }); 

    } 

感謝任何幫助或意見。

回答

0

你在正確的軌道上。假設你想點擊的元素,等待頁面轉換,然後檢查所生成的網址,你可以這樣做:

clickIDverifyURL: function (elementURL) { 
    return function (element) { 
     return this.parent 
      .then(function() { 
       return element.click(); 
      }) 

      // Wait for the page transition. This can be a sleep, or you can search for an 
      // element that should be on the new page (intern will implicitly wait for it 
      // to appear), or use pollUntil to wait for a more specific condition. 
      .sleep(1000) 

      // Get the page URL 
      .getCurrentUrl() 
      .then(function (url) { 
       assert.strictEqual(url, elementURL); 
      }); 
    } 
} 

你會用它喜歡:

.findElementByCssSelector('.someselector') 
.then(myModule.clickIDverifyURL('expectedURL')) 

clickIDVerifyURL發生在一些配置數據(預期的URL)並返回一個可以在命令的回調中調用的函數。這些函數在其上下文中具有parent屬性,該屬性引用父命令鏈(功能鏈從this.remote開始)。

請注意,元素上調用的方法,如上面的element.click(),返回Promises而不是命令。這意味着只有標準的Promise方法可以鏈接,而不是命令方法,如click,findElementByX等。這就是爲什麼上面的代碼從this.parent開始內鏈而不是element

更新

相同的基本結構適用於其他類型的輔助方法。例如,如果你想使用一個輔助方法做的發現,它可能看起來像:

findBySomething: function (selector) { 
    return function() { 
     var setContext = arguments[arguments.length - 1]; 
     return this.parent 
      .findByCssSelector(selector) 
      .then(function (element) { 
       setContext(element); 
      }); 
    } 
} 

那麼你可以做

this.remote 
    .then(myModule.findBySomething('.selector')) 
    .then(myModule.clickIDverifyURL('expected URL')) 
+0

感謝jason0x43。我現在對如何構建它有了更好的瞭解。爲元素類型創建單獨的方法是否有意義?我希望能夠使用正則表達式來分解第一個字符,以便開發人員只需將幾個元素(css選擇器,xpath或div id)交給我們即可。難道去: 'myModule.findElement( 'someselector ') 。然後(myModule.clickIDverifyURL(' expectedURL'))' 若然,應findElement是回報上以維持鏈條? – whatthestack

+0

爲此,你可以做一些類似......恩,評論對此不太好。我會更新答案... – jason0x43

相關問題