Breaking out of a Protractor .filter() or .map() loop

前端 未结 2 1124
抹茶落季
抹茶落季 2020-12-20 04:24

I\'m using Protractor and cucumber framework; how do I break out of a .filter or .map loop? I do not want to continue to iterate further if I found a match!

         


        
相关标签:
2条回答
  • 2020-12-20 04:41

    What i understood from your post is, you would like to exit loop(iterate) when find a match element.

    If yes, then better go with .filter() method. As it iterates on all available list of element finders and returns when a match finds.

    Code Snippet:
    
    element.all(by.css('.items li')).filter(function(elem, index) {
              return elem.getText().then(function(text) {
                                    if(text === 'RequiredElementFind'){
                                          return ele;//return matched element
                                     };
        });
    }).click();//only matched element comes from the loop do what would you like    
      to do
    
    0 讨论(0)
  • 2020-12-20 04:52

    You are returning a single element, so .reduce would be preferable.

    Here is a usage example to return the first link where the text is "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;
    });
    
    0 讨论(0)
提交回复
热议问题