在量角器中选择第一个可见元素

use*_*949 12 selenium protractor

我正在编写量角器测试并喜欢它,虽然有时似乎陷入了似乎应该简单的事情.例如,我想循环浏览其中一个页面上具有"Nominate"文本的所有按钮.页面上有几十个,但只有1或2个可见.所以我想点击第一个.这是我目前使用的代码:

    var nominateButtons = element.all(by.buttonText('Nominate'));
    nominateButtons.then(function(els){
        for(var x = 0;x < els.length;x++){
            //Since isDisplayed returns a promise, I need to do it this way to get to the actual value
            els[x].isDisplayed().then(function(isVisible){
                //isVisible now has the right value                 
                if(isVisible){
                    //But now els is not defined because of the scope of the promise!!
                    els[x].click();
                }
            });
        }
    });
Run Code Online (Sandbox Code Playgroud)

当我运行此代码时,我得到一个'无法调用方法点击未定义'错误,因为els [x]不再在范围内,但我似乎无法在不使用promise的情况下检查可见性.所以我的问题是,你怎么能循环遍历一系列元素,检查它们的可见性,然后点击第一个可见元素?(我试图不使用期望来检查可见性,因为我知道大多数按钮都不可见)

提前致谢

han*_*uan 16

els被定义为.什么没有定义x.简单的方法是:

var nominateButtons = element.all(by.buttonText('Nominate'));
var displayedButtons = nominateButtons.filter(function(elem) {
   return elem.isDisplayed(); 
});
displayedButtons.first().click();
Run Code Online (Sandbox Code Playgroud)

要么

element.all(by.buttonText('Nominate')).
  filter(function(elem) {
    return elem.isDisplayed(); 
  }).
  first().
  click();
Run Code Online (Sandbox Code Playgroud)

编辑,顺便说一句,你不应该依赖这种行为(点击文本'Nominate'的第一个按钮),因为它会在你更改你的应用时导致问题.看看你是否可以按ID选择,或者选择更具体的'Nominate'之类的element(by.css('the section the nominate is under')).element(by.buttonText('Nominate'));

再次编辑:请参阅使用带有循环的量角器进行说明