Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the text of all elements in protractor

I want to fetch all the li texts of suggestions after entering in the google search bar "Webdriver". I have wrote some code like this:

 this.getElements = function(){
  element.all(by.css('ul.sbsb_b')).then(function(text){
      for(var i=0; i < text.length;i++)
      {
          console.log(text[i].getText());
      }
  });
};

On execution I m getting something like:

{ ptor_: 
  { controlFlow: [Function],
     schedule: [Function],
     getSession: [Function],
     getCapabilities: [Function],
     quit: [Function],

instead of text values of Suggestions.

like image 433
Rishi Sharma Avatar asked Apr 08 '15 20:04

Rishi Sharma


4 Answers

There is a set of javascript array-like functions in Protractor that allows you to filter() or map() result of async promise. For example if original element.all(by.css('something')) would return list of ElementFinders, map() allows to transform it into array of getText()s, which in resolved state is just an array of strings. You can then use it however you want.

element.all(by.css('something')).map(function(elm) {
  return elm.getText();   
}).then(function(texts) {
  texts.forEach(...);
});
like image 95
Segg3r Avatar answered Dec 01 '22 00:12

Segg3r


We need to specify getText() to get list of text in element.all

<ul class="menu">
   <li>Home</li>
   <li> About Us</li>  
</ul> 

element.all(by.css('.menu li')).getText().then(function(menus) {
    expect(menus.length).toBe(2); //true
    console.log(menus);
});

log output

['Home','About Us']

Need more helper function

like image 43
Surendra Jnawali Avatar answered Nov 30 '22 23:11

Surendra Jnawali


For looping through every element, you can also do something like:

element.all(by.css('ul.sbsb_b')).each(function(element, index) {
    element.getText().then(function(text) {
        console.log(text);
    });
});

http://angular.github.io/protractor/#/api?view=ElementArrayFinder.prototype.each

like image 21
user3450620 Avatar answered Nov 30 '22 23:11

user3450620


To print the value from getText(), you need to resolve the promise using .then()

Something like this:

text[i].getText().then(function(textValue)
{
    console.log(textValue);
});

Regards,
Sakshi

like image 45
Sakshi Singla Avatar answered Dec 01 '22 01:12

Sakshi Singla