使用 Protractor,我如何 select 一个基于文本的列表中的 DOM 对象?

With Protractor, how can I select a DOM Object within a list based on text?

我正在尝试 select 根据产品名称从我的产品列表中选择一个产品。

我想做的是说"If an item from the list has a title that matches "鸡胸肉(200g)”然后点击按钮。

有人知道用量角器怎么写吗?

我正在努力弄清楚什么时候返回了什么,什么是承诺,什么不是,以及如何等到我得到结果后再做任何事情。

dom结构看起来像

<li ng-repeat="item in filteredItems" class="ng-scope">
  <div class="product">
    <h3 class="product-title text-uppercase ng-binding" ng-bind="item.name">Chicken Breast (200g)</h3>
    <div class="pad-top-10">
      <button class="btn btn-default btn-xs" type="button" ng-click="addItem(item)">
        <span class="product-add-label">Add Item</span>
      </button>
    </div>
  </div>
</li>

到目前为止我已经试过了:

this.Given(/^I can see "([^"]*)" on the page$/, function (productName, done) {
  element.all(by.repeater('item in filteredItems')).then(function (products) {
    for(var i = 0; i < products.length; i++){
      var title = products[i].element(by.css('.product-title'));
      title.getText().then(function (text) {
        if (text.toLowerCase() === productName.toLowerCase()) {
          console.log(text);
          // products[i] shows as undefined
          console.log(products[i]);
          done();
        }
      })
    }
  });
});

这是未测试的,但可能有帮助:

var search = "Chicken Breast (200g)";
var h3 = element(by.cssContainingText('h3.product-title', search));
var button = h3.element(by.xpath('..')).element(by.css('button'));
button.click();

经过进一步调查和 phylax 建议的一些代码,我发现这是最好的解决方案:

this.Given(/^I can see "([^"]*)" on the page$/, function (productName, done) {
  element.all(by.repeater('item in filteredItems')).then(function (products) {
    for (var i = 0; i < products.length; i++) {
      (function () {
        var title = products[i].element(by.css('.product-title'));
        var product = products[i]; 
        title.getText().then(function (text) {
          if (text.toLowerCase() === productName.toLowerCase()) {
            console.log(text);
            console.log(product);
            done();
          }
        })
      })();
    }
  });
});

你可以看到我添加了一个 (function(){}());包装器所以克服了 Webstorm 抛出的 "Mutable variable is accessible from closure" 错误,我已经在其中初始化了产品。