Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protractor get all select box (option) values

In my tests I needed to check if all the expected values are present in a select box. It took me a while but I finally created this helper function:

function getSelectValues(elementFinder)
{
  var defer = protractor.promise.defer(),
      promise = defer.promise;

  elementFinder.all(by.tagName('option')).then(function(elements)
  {
    var values = [],
        elemCount = elements.length,
        counter = 0;

    elements.forEach(function(element)
    {
      element.getAttribute('value').then(function(optionValue)
      {
        counter += 1;
        values.push(optionValue);

        if(counter === elemCount)
        {
          defer.fulfill(values);
        }
      });
    })
  });

  return promise;
}

It works but looks really ugly to me. Is there a better way to do it?

EDIT:

After another two hours of reading documentation I got my helper function reduced to:

getSelectValues: function(elementFinder)
{
  return elementFinder.all(by.tagName('option')).map(function(elem, index)
  {
      return elem.getAttribute('value');
  });
}

profileType = element(by.model('regObj.profileType'));
expect(getSelectValues(profileType)).toEqual(['', 'aa', 'bb', 'cc']);
like image 962
rzajac Avatar asked Sep 30 '14 17:09

rzajac


1 Answers

If you are using protractor > 1.3.0, you can do the following:

var values = element(by.model('regObj.profileType')).
                 all(by.tagName('option')).getAttribute('value');
expect(values).toEqual(['', 'aa', 'bb', 'cc']);
like image 176
hankduan Avatar answered Oct 22 '22 10:10

hankduan