Reputation: 8665
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.
option[selected]
and select random off other indices.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?
Upvotes: 2
Views: 1562
Reputation: 474131
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.
Upvotes: 2