javascript - 同步 Protractor Promise、变量和结果

标签 javascript protractor

好吧,我正在尝试编写这段代码,但失败了。我想要做的是确保传递给函数的索引位于页面上可用元素的范围内。如果是,则传回元素引用。

假设我有以下内容:

<ul>
  <li>First row</li>
  <li>Second</li>
  <li>Third</li>
</ul>

所以,我有这个功能:

function getRow(index) {
   // get count of rows.
   var count = $$('li').count();

   // Ensure a parameter has been passed.
   if (!index) {
      throw Error("A parameter must be supplied for function getRow. Valid values are 0 through " + count-1);
   }
   // Ensure the parameter is within bounds
   if (index < 0 || index >= count) {
      throw Error("The parameter, " + index + ", is not within the bounds of 0 through " + count-1);
   }

   return $$('li').get(index);
}

上面的代码将会失败,因为 count 并不是真正的 count,而是一个 promise 。

所以,我尝试了各种方式修改它。我认为会成功的如下:

// get count of rows.
var count;
$$('li').count().then(function(c) { count = c; });

// get count of rows.
var count = $$('li').count().then(function(c) { return c; });

我很沮丧,并尝试将整个 if block 放入 thenable 函数中,但它不会“看到”索引。

(每次我以为我已经解决了这个问题,但实际上却没有。感谢您提供的所有帮助!)

更新:

按照下面的建议,我尝试将代码修改为:

function getRow(index) {
  //get count of rows.
  var count = $$('li').count().then(function(c) {
    return function() {
      return c;
    }
  });

  protractor.promise.all(count).then(function(count) {
    // Ensure a parameter has been passed.
    if (!index) {
      throw Error("A parameter must be supplied for function getRow. Valid values are 0 through " + count-1);
    }
    // Ensure the parameter is within bounds
    if (index < 0 || index >= count) {
      throw Error("The parameter, " + index + ", is not within the bounds of 0 through " + count-1);
    }
  });

  return $$('li').get(index);
}

但它失败了,因为在 protractor.promise.all().then() block 中,index 未定义。另外,在错误消息中,我什至没有得到计数值。

> getRow(0);
A parameter must be supplied for function getRow. Valid values are 0 through 

最佳答案

我认为你必须使用 javascript 闭包才能实现它。

尝试一下:

var count = element(by.css('li')).count().then(function(c){
    return function(){
        return c
    }   
});

var value = count();

您的值应该位于“value”变量中。

PS:我现在没有 Protractor 环境来测试此代码

关于javascript - 同步 Protractor Promise、变量和结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37442902/

相关文章:

javascript - 如何通过文本 [protractor] 在 ng-table 中查找特定行

selenium - 带 Protractor 的 browserstack 报告

javascript - js.writeFile 未正确写入 Blob

javascript - 这是对总结对象数组有益的 JavaScript 重构吗?

javascript - Jquery动画回调开始下一个动画

angularjs - 是否可以使用 Protractor 来测试未模型绑定(bind)到 DOM 的变量的值?

angular - 如何使用不同的环境变量运行 Protractor e2e 测试(Angular 6)

angularjs - 重新加载 Angular 应用程序时 Protractor 测试有时会失败

javascript - d3 .data 键最初返回未定义

javascript - 类与原型(prototype)属性