Protractor - getText()返回一个Array而不是String

时间:2015-11-08 10:35:09

标签: javascript angularjs protractor angularjs-e2e

我有一个相当简单的量角器测试,应该检查ng-repeat行中的文本值。

这是我的HTML:

<div ng-repeat="destination in destinations">
    <span>{{destination.city}}, {{destination.country}}</span>
</div>

这是我的JS:

lastDestination = element.all(by.repeater('destination in destinations').row(1));
expect(lastDestination.getText()).toEqual("Madrid, Spain");

documentation for getText()州:

  

获取此元素的可见(即未被CSS隐藏)innerText,包括子元素,没有任何前导或尾随空格。

所以我希望返回行的span标记中的文本,但是在运行Protractor测试时,我得到以下错误的断言:

预期['马德里,西班牙']等于'马德里,西班牙'。

GetText()似乎返回一个数组而不是一个字符串。

我尝试解决了getText()的承诺,但仍然遇到了同样的错误:

lastDestination = element.all(by.repeater('destination in destinations').row(1));

lastDestination.getText().then(function (text) {
   expect(text).toEqual("Madrid, Spain"); 
});

我可以通过定位数组中的第一个值来解决这个问题:

expect(text[0]).toEqual("Madrid, Spain");

但我仍然想知道为什么这不起作用。

有什么想法吗?

更新:在Protractor的Github页面上有一个similar bug has been reported,因此可能是getText()函数无法正常工作。

1 个答案:

答案 0 :(得分:4)

通过文件:

// Returns a promise that resolves to an array of WebElements containing
// the DIVs for the second book.
bookInfo = element.all(by.repeater('book in library').row(1));

您试图在承诺上使用getText,您需要先解决它。

var lastDestination;
element.all(by.repeater('destination in destinations').row(1)).then(
     function(elements){
          lastDestination = elements[0];
});
expect(lastDestination.getText()).toEqual("Madrid, Spain");

来源:this answer

这是幕后发生的事情。假设您在WebElement类上调用getText()。 element将是传递给core.text.getElementText

的值

Selenium(量角器)处理要发送的参数。

如果使用WebElement,这是获取内容的代码。我不知道如果解析为数组的promise是明确的thisArg会发生什么。

explicitThisArg.getText()//the explicit thisArg is the object that the function is called from.

  core.text.getElementText = function(element) {
  var text = '';
  var isRecentFirefox =
      (goog.userAgent.GECKO && goog.userAgent.VERSION >= '1.8');

  if (isRecentFirefox || goog.userAgent.WEBKIT || goog.userAgent.IE) {
    text = core.text.getTextContent_(element, false);
  } else {
    if (element.textContent) {
      text = element.textContent;
    } else {
      if (element.innerText) {
        text = element.innerText;
      }
    }
  }

  text = core.text.normalizeNewlines_(text);
  text = core.text.normalizeSpaces_(text);

  return goog.string.trim(text);
};
相关问题