在量角器中选择第一个可见元素 [英] Select first visible element in protractor

查看:46
本文介绍了在量角器中选择第一个可见元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写量角器测试并喜欢它,尽管有时似乎会陷入一些看起来似乎应该很简单的事情.例如,我想遍历其中一个页面上包含提名"文本的所有按钮.页面上有几十个,但只有 1 或 2 个可见.所以我想点击第一个.这是我目前使用的代码:

I'm writing protractor tests and like it, although sometimes seem to get caught up on something that seems as if it should be simple. For example, I want to loop through all of the buttons on one of our pages that have text of 'Nominate'. There are dozens on the page, but only 1 or 2 will be visible. So I want to click the first one that is. Here's the code I'm using currently:

    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();
                }
            });
        }
    });

当我运行此代码时,出现无法调用未定义的方法单击"错误,因为 els[x] 不再在范围内,但我似乎无法在不使用承诺的情况下检查可见性.所以我的问题是,如何遍历元素集合,检查它们的可见性,然后单击第一个可见的元素?(我尽量不使用期望来检查可见性,因为我知道大多数按钮都不可见)

When I run this code, I get a 'cannot call method click of undefined' error, because els[x] is no longer in scope, but I can't seem to check the visibility without using the promise. So my question is, how can you loop through a collection of elements, check their visibility, and click the first one that is visible? (I'm trying not to use an expect to check visibility because I know that most of the buttons won't be visible)

提前致谢

推荐答案

els 已定义.未定义的是 x.最简单的方法是:

els is defined. What's not defined is x. The easy way to do it is:

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

element.all(by.buttonText('Nominate')).
  filter(function(elem) {
    return elem.isDisplayed(); 
  }).
  first().
  click();

编辑,顺便说一句,您不应该依赖此行为(单击文本提名"的第一个按钮),因为它会在您更改应用程序时导致问题.看看你是否可以通过 ID 选择,或者选择一个更具体的提名",比如 element(by.css('the section the nominate is under')).element(by.buttonText('Nominate'));

EDIT, by the way, you shouldn't rely on this behavior (click first button of text 'Nominate') because it will lead to issues when you change your app. See if you can either select by ID, or select a more specific 'Nominate' like element(by.css('the section the nominate is under')).element(by.buttonText('Nominate'));

再次有关说明,请参阅将量角器与循环一起使用

这篇关于在量角器中选择第一个可见元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆