2

I want to handle a test scenario for a select menu where spec would pick a random option other than the one currently selected. I can't seem to find a working locator or method that would let me do it.

  1. Strategy 1: get the current index of option[selected] and select random off other indices.
  2. Strategy 2: get options not selected by.css('option:not([selected])') - get the length of the array and pick random one. This selector seems to ignore the :not part and returns total number of options.

As I am fresh to protractor, I don't really see a way to do that looking at the API. Any hint, please?

user776686
  • 7,933
  • 14
  • 71
  • 124

1 Answers1

2

First, let's filter non-selected options using .filter():

var nonSelectedOptions = $$("option").filter(function (option) {
    return option.isSelected().then(function (isSelected) {
        return !isSelected;
    });;
});

Now, we need a list of indexes to choose a random one from, let's use .map():

var indexes = nonSelectedOptions.map(function (option, index) {
    return index;
});

Now, we need to resolve the indexes promise to get the array of indexes and use the "picking a random item from an array" solution from this answer. We are going to use .get() to get a specific option for the randomly chosen index:

indexes.then(function (indexes) {
    var randomIndex = indexes[Math.floor(Math.random()*indexes.length)];

   var randomOption = nonSelectedOptions.get(randomIndex);

   // now select the randomOption
});

If you would use the wrapper suggested here, the option selection code would be:

randomOption.getAttribute("value").then(function (optionValue) {
    mySelect.selectByValue(optionValue);
});

Not tested.

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Works like a charm, thanks! I will explore the area of wrappers soon when I get more foundation. I would certainly add `SelectWrapper.prototype.selectAnother` function to the wrapper you mention. – user776686 Jan 21 '16 at 22:02