2014-09-03 43 views
1

我已經在Nightwatch中爲我的UI測試創建了此自定義命令。這是在充分:Nightwatch:使用自定義命令遍歷所有選擇的標籤

exports.command = function(element, callback) { 

    var self = this; 

    try { 

    this.waitForElementVisible('body', 15000); 
    console.log("trying.."); 
    window.addEventListener('load', function() { 

     var selects = document.getElementsByName("select"); 
     console.log(selects); 

    }, false); 


    } catch (err) { 
    console.log("code failed, here's the problem.."); 
    console.log(err); 
    } 

    this 
    .useXpath() 
    // click dropdowns 
    .waitForElementVisible(element, 15000) 
    .click(element) 
    .useCss() 
    .waitForElementVisible('option[value="02To0000000L1Hy"]', 15000) 
    // operation we want all select boxes to perform 
    .setValue('option[value="02To0000000L1Hy"]', "02To0000000L1Hy") 
    .useXpath() 
    .click(element + '/option[4]'); 

    if (typeof callback === "function") { 
    callback.call(self); 
    } 
    return this; // allows the command to be chained. 

}; 

什麼我試圖做的是網頁加載完畢後,我想檢索所有的選擇框,並對其執行相同的操作。除try/catch塊中的代碼外,所有內容都正常工作。我不斷收到'[ReferenceError:window is not defined]',我不確定如何通過它。

回答

4

「窗口」屬性在全局範圍內未定義,因爲它是通過命令行節點運行的,而不是像最初可能假設的那樣在瀏覽器中運行。

你可以嘗試使用this.injectScript從夜巡API,但我會建議使用Selenium的協議API 'elements'

0

嘿@logan_gabriel,

你也可以使用execute命令我使用的時候我需要在實際頁面上注入一些JavaScript。正如@Steve Hyndig所指出的那樣,你的測試運行在Node上而不是實際的瀏覽器窗口上(有點令人困惑,因爲一個窗口通常是在測試運行時打開的!除非使用PhantomJS來進行無頭測試)。

下面是一個示例自定義命令,它會注入一些JavaScript到基於您的原始信息的頁面:

exports.command = function(callback) { 
    var self = this; 

    this.execute(function getStorage() { 
    window.addEventListener('load', function() { 
     let selects = document.getElementsByName('select'); 
     return selects; 
    } 
    }, 

    // allows for use of callbacks with custom function 
    function(result) { 
    if (typeof callback === 'function') { 
     callback.call(self, selects); 
    } 
    }); 

    // allows command to be chained 
    return this; 
}; 

,你可以從你的測試使用下面的語法,包括一個可選的回調做一些事情打電話其結果:

client 
    .setAuth(function showSession(result) {  
    console.log(result);  
}); 

您可以選擇只是做自定義函數內的工作,但我碰上由於Nightwatch的異步性質問題有時如果我不回調的窩裏面的東西,所以這是更安全的事情。

祝你好運!