量角器无限循环

Protractor infinite loop

在上一个问题中,我在点击按钮时遇到问题,直到它被禁用答案是:

var nextPage = function () {
    if (element(by.css('[ng-click="vm.nextPage()"]')).isEnabled()) {
        element(by.css('[ng-click="vm.nextPage()"]')).click();
        nextPage(); // next page
    }
    else {
        return; // the element is not enabled, last page
    }
}

我不得不稍微更改一下,所以我的代码现在看起来像这样

 var nextPage = function() {
  if (element(by.id('next')).isEnabled()) {
    element(by.id('next')).click().then(function() {
      browser.sleep(1000);
      nextPage(); // next page
      return;
    });
  } else {
    return; // the element is not enabled, last page
  }
  return;
}

但是现在跳入无限递归调用无法执行下一步,我怎么改不了,不使用.then函数根本不起作用

问题是 递归基本情况从未满足 并且它从不存在递归。

请记住,量角器中的一切都是一个承诺isEnabled() 在你的情况下是一个未解决的承诺,它始终是 "truthy"。这就是为什么不管真正的 isEnabled 值总是进入下一个循环并最终得到最大递归深度误差的原因。

显式解析 promise 以获得真正的 isEnabled 布尔值:

element(by.id('next')).isEnabled().then(function (isEnabled) {
    if (isEnabled) {
        // ...
    } else {
        return; // the element is not enabled, last page
    }
});

作为旁注,无耻的宣传 本来可以帮助更早地解决这个问题 - eslint-plugin-protractor and it's rule to catch when protractor promises are used inside if conditions directly without being explicitly resolved。如果针对问题中发布的代码执行,它会输出以下内容:

$ eslint test.js
/path/to/test.js
  2:5   warning  Unexpected "isEnabled()" inside if condition  protractor/no-promise-in-if 
  4:13  warning  Unexpected browser.sleep()                    protractor/no-browser-sleep