Reputation: 97
I'm trying to run the following code (a number of steps) several times (e.g: 10 times) so that:
I'm working with the following NightwatchJS code:
var randomEmail = faker.internet.email()
var competitionReference = ['drawing_21715','drawing_21704']
var randomCompetitionReference = competitionReference[Math.floor(Math.random()*competitionReference.length)]
module.exports = {
'navigate to homepage': function (browser) {
browser
.url('http://clickswin-stage.bellamagazine.co.uk/')
},
'select a competition': function (browser) {
browser
.useXpath()
.click('//*[@id="' + randomCompetitionReference + '"]/div/div[1]')
},
};
I've read that the best way to do this would be to use a while loop, but I'm not really sure how to set this up for my code above.
For example, if I were to use:
var i = 0
while ( i < 10) {
etc, whereabouts would I need to put this loop code within my code above?
Any help would be greatly appreciated.
Upvotes: 0
Views: 842
Reputation: 61
One solution could be using a recursive function. Here is an example of how this could look like:
var randomEmail = faker.internet.email()
var competitionReference = ['drawing_21715', 'drawing_21704']
// var randomCompetitionReference = competitionReference[Math.floor(Math.random() * competitionReference.length)]
var randomCompetitionReference = function() {return competitionReference[Math.floor(Math.random() * competitionReference.length)]}
module.exports = {
'navigate to homepage': function (browser) {
browser
.url('http://clickswin-stage.bellamagazine.co.uk/')
},
'select a competition': function (browser, recursions) {
// Put the main code into a separat recursive function.
const doClick = function(times) {
if (times > 0) { // This is the equivalent to "while ( i < 10) {"
return browser
.useXpath()
.click('//*[@id="' + randomCompetitionReference() + '"]/div/div[1]')
.useCss()
.perform(()=>{ // perform() makes sure, that one function call is only executed after the other has fineshed (not concorrent)
return doClick(times -1)
})
} else {
return browser
}
}
doClick(recursions)
}
}
In your case you would call the function 'select a competition' with 10 as the parameter "recursions".
Note that I have changed "randomCompetitionReference" to be a function, so this generates a different value every time it is called. Else it would get one random value when its defined, and would reuse that same value for every click().
Upvotes: 1