Protractor使用element.all检查LIST上是否存在元素



我需要做一个断言来检查'elements.all'中是否存在元素。

我的第一个想法是运行一个for循环,并在里面放入一个期望。这不是一个好主意,因为它正在检查列表中的每一项。所以,如果我有30个项目,我可能会有29个失败。

element.all(by.css(element)).then(function(itemList) {
  console.log("Total values in dropdown are: " + itemList.length);
  for (i = 0; i < itemList.length; i++) {
    itemList[i].getText().then(function(text) {
      console.log(text);
      expect(text).toEqual('whatever-i-need-to-assert');
    });
  };
});

为了解决这个问题,我嵌套了一个IF语句,它将"预检查"字符串匹配。另一个坏主意是,如果没有对手,我的期望永远不会运行,因此,给了我一个错误的通行证:

element.all(by.css(".item a.gc-exercises-link")).then(function(itemList) {
  console.log("Total values in dropdown are: " + itemList.length);
  for (i = 0; i < itemList.length; i++) {
    itemList[i].getText().then(function(text) {
      console.log(text);
      if (text == 'BOATLIFT-EXERCISE') {
        console.log('Match');
        expect(text).toEqual('BOATLIFT-EXERCISE');
      } else {
        console.log('No Match');
      };
    });
  };
});

很明显,我走错了路。有人能告诉我在使用element.all时如何正确地期望"文本"吗?我只需要证明所述列表中存在文本。

谢谢!

下面是一个检查页面中是否有文本为"Terms"的链接的示例:

browser.get('https://www.google.co.uk/');
expect(element.all(by.css('a')).getText()).toContain('Terms');

请注意,对于每个元素,量角器都需要对浏览器进行互操作,这可能会很慢,尤其是在有很多元素的情况下。

一个更快的解决方案是检查是否至少有一个元素存在XPath,其中包括预期的文本:

browser.get('https://www.google.co.uk/');
expect(element.all(by.xpath("//a[text()='Terms']")).count()).toBeGreaterThan(0);

如果你只想检查它是否存在(其他列表项不会干扰),你可以在element.all之后、.then之前的数组上调用.getText(),并使用toContain()

element.all(by.css(".item a.gc-exercises-link")).getText().then(function(itemList) {
    expect(itemList).toContain('some text');
};

或者如果你知道索引:

element.all(by.css(".item a.gc-exercises-link")).getText().then(function(itemList) {
    expect(itemList[3]).toEqual('some text');
}

附带说明:您可以使用.each()而不是创建for循环https://angular.github.io/protractor/#/api?view=ElementArrayFinder.prototype.each

您可以使用过滤器功能。

$$("span").filter(function(elem,index){
    return elem.getText().then(function(txt){
        return txt === 'text to compare';
    });
}).then(function(eleList){   // you get the list of elements containing the text here
    console.log(eleList.length);
});

最新更新