I have a situation where I'm using protractor to click a random link on the page. (There are a lot). I have an array of links that I don't want to click, so I want to know when my random link is in that array and generate a new random link.
Here's my working code to click a random link on the page
var noClickArray = ['link2', 'link3']; // array much bigger than this
var parent = this;
function() {
var links = element.all(by.css('.links'));
return links.count().then(function(count) {
var randomLink = links.get(Math.floor(Math.random() * count));
randomLink.getText().then(function(text) {
parent.selectedLink = text; // used in a different function
var containsLink = _.includes(noClickArray, text);
});
return randomLink.click();
});
}
I'm using lodash to find if the randomLink
text is in noClickArray
but I don't know how to keep generating random values until the value does not exist in the array. How can I do this?
I think you are overcomplicating the problem.
I would just filter out links you don't want to click using filter()
beforehand:
function() {
var links = element.all(by.css('.links'));
links = links.filter(function (link) {
return link.getText().then(function(text) {
return !_.includes(noClickArray, text);
});
});
return links.count().then(function(count) {
var randomLink = links.get(Math.floor(Math.random() * count));
return randomLink.click();
});
}
You could simply use a recursive call until you get a non black listed link. This way, you will avoid the cost of getting the text for all the links:
function() {
return element.all(by.css('.links')).then(function clickRandom(links) {
// remove a random link from the array of links
var link = links.splice(Math.floor(Math.random() * links.length), 1)[0];
return link && link.getText().then(function(text) {
if(noClickArray.indexOf(text) === -1) { // if not black listed
return link.click(); // click link
}
return clickRandom(links); // try again
});
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With