Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all visible elements using Protractor

I am trying to the count of find all visible elements under a container using Protractor

function getVisibleDivs(driver) { 
  var links = driver.findElements(by.css("#MainContent div")); 
  return protractor.promise.filter(links, function(link) { 
    link.isDisplayed(); 
   })
  .then(function(visibleLinks) {
      return visibleLinks; 
    }); 
}

element.all(getVisibleDivs).then(function (items) {
        console.log(items.length);
});

I always get the count as 0 though I have manually checked that the elements are present. Any pointers for debugging this much appreciated.

UPDATE Some sample html

<html>
    <body>
        <div id="MainContent">
            <div class="header">
                Header
            </div>
            <div class="content">
                Content
            </div>
            <div class="sidebar" style="display:none">
                Sidebar
            </div>
            <div class="footer">
                Footer
            </div>
        </div>
    </body>
</html>
like image 794
Gautham Avatar asked May 26 '14 05:05

Gautham


2 Answers

There is no need to use protractor.promise directly. Protractor exposes functional programming functions like filter() on ElementArrayFinder - the result of element.all().

Here is how to use it:

var visibleDivs = $$("#MainContent div").filter(function(link) { 
    return link.isDisplayed();
});

expect(visibleDivs.count()).toEqual(3);
like image 180
alecxe Avatar answered Oct 06 '22 00:10

alecxe


Your filter function does not return anything, so add 'return' to link.isDisplayed():

function getVisibleDivs(driver) { 
  var links = driver.findElements(by.css("#MainContent div")); 
  return protractor.promise.filter(links, function(link) { 
    return link.isDisplayed(); 
   })
  .then(function(visibleLinks) {
      return visibleLinks; 
    }); 
}

element.all(getVisibleDivs).then(function (items) {
        console.log(items.length);
});
like image 39
Alex Paramonov Avatar answered Oct 06 '22 00:10

Alex Paramonov