我是 javascript 和 nightwatch js 的新手。
我正在尝试自动化在线测试,该测试最多有 4 到 5 个问题,这些问题是随机生成的。每个问题都会加载一个新页面,因此基本上您回答一个问题,提交它,然后显示下一个问题。
答案可以有不同的类型,有些是“是/否”按钮,有些是您单击的多项选择,有些是在文本字段中输入数据,然后您必须按 Enter 键提交键盘上的 键。幸运的是,用于每种类型答案的定位器始终相同(不是动态生成的)。例如。是/否问题,"is"答案将始终为 .answerYes,或者如果是文本字段,则始终为 #answerBox。
我需要回答 4 或 5 个问题,如果我回答正确并不重要。
我正在考虑使用 for 循环,检查是否获得了我已经确定的这些元素之一,如果是,我会执行该操作并继续下一页,直到调查问卷完成。
我想到了类似下面的例子。我认为这行不通,因为 javascript 是异步的——我还没有完全理解。
for (i = 0; i < 10; i++) {
if (client.waitForElementVisible('.element1',1000)) {
client.click('.element1'); //This would select first answer
client.click('nextButton'); //This would continue to the next question
}
else if (client.waitForElementVisible('.element2',1000)) {
client.click('.element2'); //This would select first answer
client.click('nextButton'); //This would continue to the next question
}
else if (client.waitForElementVisible('.element3',1000)) {
client.click('.element3'); //This would select first answer
client.click('nextButton'); //This would continue to the next question
}
else if (client.waitForElementVisible('.element4',1000)) {
client.click('.element4'); //This would select first answer
client.click('nextButton'); //This would continue to the next question
}
else if (client.waitForElementVisible('.element5',1000)) { //element 5 would be the confirmation that test is over
client.click('.element5'); //this would click the OK button when notified test is done
leaveTheLoop(); //Not sure what would be the command to leave the loop
}
}
我还在查看 JavaScript 的 Switch 语句,但我不认为我可以在表达式中编写一些内容来验证我期望的任何元素是否会全部出现在一个表达式下。
最佳答案
你可以继续链接
.waitForElementVisible(selector,timeout,abortOnFailure,callback)
检查元素是否可见。
通过将abortOnFailure
设置为false
,这样整个测试就不会失败,即使element1不可见,您也可以继续进行element2,3,4,5。
这是代码:
test(client){
client.waitForElementVisible('.element1',1000,false,function(){
client.click('.element1'); //This would select the first answer
.click('nextButton');
})
.waitForElementVisible('.element2',1000,false,function(){
client.click('.element2'); //This would select the second answer
.click('nextButton');
})
.waitForElementVisible('.element3',1000,false,function(){
client.click('.element3'); //This would select the third answer
.click('nextButton');
})
.waitForElementVisible('.element4',1000,false,function(){
client.click('.element4'); //This would select the forth answer
.click('nextButton');
})
.waitForElementVisible('.element5',1000,false,function(){
client.click('.element5'); //This would select the fifth answer
})
}
详细说明: http://nightwatchjs.org/api/#waitForElementVisible
用法:
do{
test(client);
client.click('submit_or_whatevertothenextpage');
}while (client.except.to.not.be.visible(".result_element_non_existing"));
关于javascript - 在循环内使用条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45743653/