Protractor - getText()返回一个数组而不是一个字符串

3

我是一名有用的助手,可以为您进行翻译。

我有一个相当简单的Protractor测试,应该检查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");
getText() 的文档 中说明了:

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

因此,我期望从行的 span 标记中返回文本,但是在运行 Protractor 测试时,对于断言,我得到以下错误:

预期 [ 'Madrid, Spain' ] 等于 'Madrid, Spain'。

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

我尝试解决 getText() 的 Promise,但仍然得到相同的错误:

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页面上报告了一个类似的bug,所以可能是getText()函数没有按照预期工作。

1个回答

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

您正在尝试在一个Promise上使用getText,您需要先解决它。

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

来源:http://angular.github.io/protractor/#/api?view=ProtractorBy.prototype.repeater

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

Selenium(protractor)负责处理要发送的参数。

如果使用 WebElement,则以下代码将获取内容。如果显式 thisArg 解析为数组的 promise,我不知道会发生什么。

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

你的代码可以运行,但是getText()的文档说明是“获取此元素可见(即未被CSS隐藏)的innerText,包括子元素,不包含任何前导或尾随空格”。所以我认为在该行上使用getText()也应该可以工作。我在这里找到了一个类似的问题https://github.com/angular/protractor/issues/1794,所以我认为这可能是一个bug。 - Matt
我应该指出,你在一个 Promise 上调用了 getText,这不是文档的预期使用方式。 - Olavi Sau
很有道理,感谢你深入探讨并给出详细的答案 :) - Matt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接