我是javascript和nightwatch js的新手。在循環中使用條件
我試圖自動化一個在線測試,其中最多有4到5個問題是隨機生成的。每個問題都會出現在新的頁面上,所以基本上你會回答一個問題,提交它,然後再呈現下一個問題。
答案可以是不同的類型,其中一些是YES/NO按鈕,其中一些是您單擊的多項選擇,其中一些是將數據輸入到文本字段中,然後您必須通過按在鍵盤上輸入鍵。幸運的是,用於這些類型答案的每一個的定位符總是相同的(不是動態生成的)。例如。是/否問題,是的答案將始終是.answer是或者如果它的文本字段將始終是#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
}
}
我也看着switch語句的JavaScript,但我不認爲我可以在表達寫東西,如果任何我期待的元素將出現在所有的一個表達,將驗證。
您好,感謝回答。但我確實需要一個循環,因爲問題和答案是隨機生成的,所以我可能會一遍又一遍地得到相同類型的答案。使用你的代碼,一旦發現,它會完成。 – Sparda2
更新了答案,但有點愚蠢的做法,因爲您沒有在每次測試後描述行爲,所以只需將上面的代碼轉換爲方法並重用它。 – Raymond