如何在PROTRACTOR中获取元素的索引

时间:2016-06-30 14:07:37

标签: javascript angularjs protractor

这是我的第一个问题,我一直在尝试使用Protractor进行端到端测试。 我需要从这组代码中获取第一个元素。如您所见,我对这3个元素有相同的类和相同的子类。所以我想通过使用索引得到它。

    <div class="col-md-4">
          <div class="form-group">
            <label>Número</label>
            <input class="form-control ng-valid ng-touched ng-dirty" type="number">
          </div>
        </div>
<div class="form-group">
        <label>Inicio Vigência</label>
        <input class="form-control ng-untouched ng-pristine ng-valid" placeholder="dd/MM/yyyy" type="date" value="">
      </div>
<div class="form-group">
        <label>Fim Vigência</label>
        <input class="form-control ng-untouched ng-pristine ng-valid" placeholder="dd/MM/yyyy" type="date" value="">
      </div>

我在尝试:

var numero = element.all(by.className('form-group')).get(2).all(by.tagName('input'));
        numero.sendKeys(aux2);

但它不起作用。量角器不会在输入中发送密钥。

1 个答案:

答案 0 :(得分:0)

好吧,如果您需要第一个元素,只需使用.first()代替.get(2)

var numero = element.all(by.className('form-group')).first().all(by.tagName('input'));
numero.sendKeys(aux2);

请注意,您可以使用CSS选择器和first-of-type pseudo-class一起找到所需的输入元素:

var numero = $(".form-group:first-of-type input");
numero.sendKeys(aux2);

或者,通过nth-of-type()

var numero = $(".form-group:nth-of-type(1) input");
numero.sendKeys(aux2);

$这里是convenient shortcutelement(by.css())

解决这个问题的另一种方法是不依赖于表单组索引(实际上听起来很脆弱 - 想象UI会改变,表单控件只会被重新排列),而是找到{{1基于它的标签的元素:

input