量角器在for循环中中断while

Protractor break while of for loop

本文关键字:中断 while 循环 for 量角器      更新时间:2023-09-26

我需要帮助环喙。

我做了一个简单的测试:

while(i < 10) {
    element(by.xpath("//a[contains(@id, 'ma-apply')]")).isPresent().then(function(result) {
        if(!result) {
            helper.one_page_ahead();
        } else {
            console.log('there is on the page');
            break;
        }
    });
    i++;
};

这段代码导致错误。

我试图通过StackOverflow遵循建议,并将break更改为返回。但是这会导致整个循环执行(最多10个)。

输出如下:

[14:17:46] I/launcher - Running 1 instances of WebDriver Started user技巧:AJAX有页面就有页面就有页面这一页有这一页有这一页有这一页有这一页There is on the page .

1 spec, 0 failure in 37.93秒完成

我尝试了同样的for循环,如

for(i = 0; i < 10; i++) {
    //code
    break;
}

我很乐意找到答案。

这是关于为什么while语句不工作的一些评论:当您调用isPresent时,您返回webdriver.promise.Promise<boolean>。因为你在webdriver控制流中,你需要抛出一个错误,

      browser.get('http://angularjs.org');
      var i = 0;
      var running = true;
      while(i < 3 && running) {
        console.log('while: ' + running + ' ' + i);
        element(by.model('username')).isPresent().then((result) => {
          console.log('element: ' + running + ' ' + i);
          if (result) {
            // huzzah we found it, so lets break the element after the first test
            browser.get('https://docs.angularjs.org/tutorial');
          } else {
            running = false;
            throw new Error('no username')
          }
        }).catch((err) => {
          console.log(err);
        });
        i++;
      }

这基本上打印出:

[19:07:18] I/hosted - Using the selenium server at http://localhost:4444/wd/hub
[19:07:18] I/launcher - Running 1 instances of WebDriver
Started
while: true 0
while: true 1
while: true 2
element: true 3
[Error: no username]
element: false 3
[Error: no username]
element: false 3
[Error: no username]

所以基本上你的while循环在控制流中排队等待执行。然后这些将按顺序异步执行。

我喜欢Sudharsan Selvaraj递归的建议

您需要实现recursive方法来实现您想要的,请尝试下面的代码,

function runTillElementFound(totalCount,currentCount){
  var self = this;
  var _element = element(by.xpath("//a[contains(@id, 'ma-apply')]"));
  if(currentCount < totalCount){
     return _element.isPresent().then(function(isElementPresent){
        if(isElementPresent){
           return;
         }else{
           helper.one_page_ahead();
           self.runTillElementFound(totalCount,currentCount++);
         }
      })
  }else{
     return false; //if element not present after Max count reached.
   }
}
this.runTillElementFound(10,0); //this will execute the method untill the required element found on the page.

如果想避免递归,可以在返回的承诺

中修改索引变量。
while(i < 10) {
element(by.xpath("//a[contains(@id, 'ma-apply')]")).isPresent().then(function(result) {
    if(!result) {
        helper.one_page_ahead();
    } else {
        console.log('there is on the page');
        i = 10;
    }
});
i++;

};

并且我会在每次重复之间添加一个browser.sleep(x),以避免在promise的结果被评估之前运行代码。

i = 10;仍然循环迭代