如何检查Protractor中的列中是否找到文本

时间:2014-09-13 18:00:34

标签: protractor

我正在尝试断言名称显示在表的列中。我编写了一个inResults函数,它将迭代列的文本以查看是否存在名称。这是我正在尝试的:

页面对象:

this.names = element.all(by.repeater('row in rows').column('{{row}}'));

this.inResults = function(nameString) {
    var foundit = '';
    this.names.each(function(name) {
        name.getText().then(function(it) {
            console.log(it); // each name IS printed...
            if(it == nameString) {
                console.log('it\'s TRUE!!!!'); // this gets printed...

                foundit = true;
            }
        });
    });
    return foundit; // returns '' but should be true?
};

Spec expect:

expect(friendPage.inResults('Jo')).toBeTruthy();

两个控制台语句都按预期打印...但我的期望失败,因为foundit的值仍为''。我已经尝试了很多方法而且都没有。我错过了什么?

3 个答案:

答案 0 :(得分:6)

我已经设计出了我认为更好/更清洁的方法来解决这个问题。它不那么复杂,并且在方法中不需要定位符/ css代码。

friend.page.js

// locator
this.friendName = function(text) { return element.all(by.cssContainingText('td.ng-binding', text)) };

// method
this.inResults = function(name) {
    return this.friendName(name).then(function(found) {
        return found.length > 0;
    });
};

friend.spec.js

expect(friendPage.inResults('Jo')).toBeTruthy();

我已将此添加到我的protractor_example project on GitHub ...

答案 1 :(得分:3)

我建议您使用过滤器:http://angular.github.io/protractor/#/api?view=ElementArrayFinder.prototype.filter

this.inResults = function(nameString) {    
  return this.names.filter(function(name) {
    return name.getText().then(function(text) {          
      return text === nameString;
    });
  }).then(function(filteredElements) {
    // Only the elements that passed the filter will be here. This is an array.
    return filteredElements.length > 0;
  });
});

// This will be a promise that resolves to a boolean.
expect(friendPage.inResults('Jo')).toBe(true);

答案 2 :(得分:2)

使用map执行此操作。这将返回一个将使用数组中的值解析的延迟,所以如果你有这个:

this.mappedVals =element.all(by.repeater('row in rows').column('{{row}}')).map(function (elm) {
    return elm.getText();
});

它会像这样解决:

this.inResults = function(nameString) {
  var foundit = '';
  mappedVals.then(function (textArr) {
    // textArr will be an actual JS array of the text from each node in your repeater
    for(var i=0; i<textArr.length; i++){
       if(it == textArr[i]) {
            console.log('it\'s TRUE!!!!'); // this gets printed...
            foundit = true;
        }
    }
    return foundit;
  });
}

并在Spec文件中使用它,如

friendPage.inResults('Jo').then(function(findIt){
  expect(findIt).toBeTruthy();
});
相关问题