我正在尝试多次(例如10次)运行以下代码(若干步骤),以便:
我正在使用以下 NightwatchJS 代码:
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]')
},
};
我已经读到,执行此操作的最佳方法是使用 while 循环,但我不确定如何为上面的代码进行设置。
例如,如果我要使用:
var i = 0
while ( i < 10) {
等等,我需要把这个循环代码放到上面的代码中吗?
任何帮助将不胜感激。
答案 0 :(得分:1)
一个解决方案可能是使用递归函数。这是一个看起来像这样的示例:
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)
}
}
在您的情况下,您将使用10作为参数“递归”来调用“选择比赛”功能。
请注意,我已将“ randomCompetitionReference”更改为一个函数,因此每次调用它都会生成一个不同的值。否则,它在定义时将获得一个随机值,并将为每个click()重用相同的值。