Reputation: 1280
I am trying to automate some UI testing with nightwatch.js, I need to select a random value from the drop down which looks like the code below.
<select class="form-control" name="drop_ddl" id="drop_ddl">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
As of now I am using an approach where I have no reliability in case the random number I have selected doesn't exist in the drop down option values.
var drop_ddl=Math.floor((Math.random() * 8) + 1);
return this.client.click("#drop_ddl option[value='"+drop_ddl+"']");
In case the random number is say 6 which doesn't appear in the list it will fail the further tests.
Is there a way we can read the values to an array and then select randomly out of these available values only ?
Upvotes: 1
Views: 3037
Reputation: 1640
Came across similar case, when you have to select random Radio button. This is a bit tricky - you can't really use :nth-child
selector, because bloody bastards could be spread all over the place. In this case you can use:
exports.command = function (selector, value) {
this
.elements('css selector', selector, res => {
if (res.value.length) {
let random = Math.floor(Math.random() * res.value.length);
let el = res.value[random].ELEMENT;
this.elementIdClick(el);
}
});
return this;
};
Upvotes: 0
Reputation: 101
Use elements
to get all the drop down options.
browser.elements('css selector', '#drop_ddl option', function(result) {
return result.value.length;
})
Now that you have the number of options, use nth-child to select a random option.
var drop_ddl=Math.floor((Math.random() * optionsLength) + 1);
return this.client.click("#drop_ddl option:nth-child(drop_ddl)");
Upvotes: 2
Reputation: 2864
How about adding sequential IDs to the options?
<select class="form-control" name="drop_ddl" id="drop_ddl">
<option id="1" value=""></option>
<option id="2" value="1">1</option>
<option id="3" value="2">2</option>
<option id="4" value="3">3</option>
<option id="5" value="4">4</option>
<option id="6" value="7">7</option>
<option id="7" value="8">8</option>
<option id="8" value="9">9</option>
<option id="9" value="11">11</option>
<option id="10" value="12">12</option>
</select>
<script>
var drop_ddl=Math.floor((Math.random() * 10) + 1);
$("#drop_ddl option[id='" + drop_ddl + "']").attr("selected", "selected");
</script>
Upvotes: 0