selenium - 打破 Protractor .filter() 或 .map() 循环

标签 selenium protractor browser-automation e2e-testing webautomation

我正在使用 Protractor 和 cucumber 框架;如何跳出 .filter 或 .map 循环?如果找到匹配项,我不想继续进一步迭代!

Page.prototype.getElementByKey = function (key) {
      var foundElement = null;
      return someElement.all(by.css('.someClass')).map(function (rawItem, index) {
        var itemObject = new ItemObjectClass(rawItem);
        return itemObject.getItemKey().then(function (foundItemKey) {
          var matched = String(foundItemKey).trim() === String(key).trim();

         console.log(' Matched: { ' + matched + ' }  index {'+index+'}');
          //if we have a match break out of the .filter function
          if (matched) {
            foundElement = itemObject;
            throw new Error("Just our way of breaking out of .filter() above");
          }
        });
      }).then(function () {
        //callback
        throw new Error('\n!!!!!Callback should not be called; 
       this means that we could not find an element that matched the passed in key above');
      }, function (error) {
        //error
        console.log('\n*******************errorCallback was called; '+error);
        return foundElement;
      });
    };

上面的代码找到了元素,但继续迭代直到结束,而不是在有匹配项时停止并通过调用 errorCallback 函数中断。

考虑到 .map 函数返回“解析为 map 函数返回的值数组的 promise http://www.protractortest.org/#/api?view=ElementArrayFinder.prototype.map ,我正在利用这样一个事实,即如果 promise 无法解决, promise 将调用其 errCallback。

通过抛出一个假错误,应该调用 errorCallback 从而跳出 .map 循环。

不幸的是,它成功抛出错误但继续循环而不是中断。我知道,因为当我

console.log("boolean "+matched+" and index "+index);

我明白了:

matched: false index: 0
matched: false index: 1
matched: true index 2 //it should have stopped here since matched = true
matched false index 3 // this should NOT have printed

那么爆发是行不通的吗?

最佳答案

您返回的是单个元素,因此 .reduce 会更可取。

这是一个返回文本为“mylink”的第一个链接的用法示例:

var link = element.all(by.css('a')).reduce(function (result, elem, index) {
    if(result) return result;

    return elem.getText().then(function(text){
        if(text === "mylink") return elem;
    });

}).then(function(result){
    if(!result) throw new Error("Element not found");
    return result;
});

关于selenium - 打破 Protractor .filter() 或 .map() 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38777577/

相关文章:

python - Protractor 的预期条件

javascript - 在 Puppeteer 中如何从默认配置文件切换到 chrome 窗口到所需的配置文件

python - 从soapui运行selenium python测试来读取文件

php - Selenium 测试用例返回 Process finished with exit code 0

javascript - Protractor - 请参阅页面上的文字

angularjs - 作为 Maven 构建过程的一部分运行 Protractor 测试

python - Selenium:如何在 AWS 上使用 Headless Chrome?

c# - 这个目录结构是否足以用于 Selenium Test + C#

python - 当我尝试处理该警报时获取 "Exception UnexpectedAlertPresentException: Alert Text: None"然后获取 "Exception NoAlertPresent"

java - 如何使用 Selenium Webdriver 单击带空格的 CSS