2014-09-03 42 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的异步性质问题有时如果我不回调的窝里面的东西,所以这是更安全的事情。

祝你好运!