0
我有兩個測試,test1和test2。當我運行測試時,測試1將成功,測試2將失敗或測試2將成功,而測試1將失敗。這兩個測試都涉及點擊一個按鈕,通過一些jquery方法更新DOM。看起來只有首先運行的測試纔會觸發這些方法,有沒有人知道這是爲什麼?qunit測試交替失敗
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript tests</title>
<link rel="stylesheet" href="http://code.jquery.com/qunit.css">
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture">
<div id="div1">
<button class="selected">Property1</button>
<button >Property2</button>
</div> <!-- div1 -->
<div id="div2">
<table>
<tbody>
<tr>
<th>Name</th>
<td></td>
</tr>
<tbody>
</table>
</div> <!-- div2 -->
<script src="http://code.jquery.com/jquery.min.js"></script>
<script>
$("#div1 button").click(function(){
console.log("button clicked");
$(this).addClass("selected"); // clicked button is set to selected
var nameElement = $("#div2 table td");
nameElement.text($(this).text()); // updates the nameElement to the text contents of the button clicked
var buttons = $(this).parent().find("button");
for(i=0; i<buttons.length; i++){
if(buttons[i] != $(this)[0]){
$(buttons[i]).removeClass("selected") // other buttons are set to unselected
}
}
});
</script>
</div> <!-- qunit-fixture -->
<script src="http://code.jquery.com/qunit/qunit-1.19.0.js"></script>
<script>
test("test clicking on a property button adds the selected class to it", function(){
console.log("test1");
var buttons = $("#div1 button");
$(buttons[1]).click();
equal($(buttons[0]).hasClass("selected"), false);
equal($(buttons[1]).hasClass("selected"), true);
$(buttons[0]).click();
equal($(buttons[0]).hasClass("selected"), true);
equal($(buttons[1]).hasClass("selected"), false);
console.log("end of test1");
});
test("test clicking on a property button updates the property details", function(){
console.log("test2");
var buttons = $("#div1 button");
var name = $("#div2 table td");
buttons[1].click()
equal(name.text(), "Property2")
console.log("end of test2");
});
</script>
</body>
</html>
控制檯的輸出顯示按鈕點擊僅在第一個運行的測試中註冊。例如
test.html:49 test1
test.html:31 button clicked
test.html:31 button clicked
test.html:61 end of test1
test.html:66 test2
test.html:74 end of test2
謝謝,這是做了很大的意義。我正在修改我在教科書中閱讀的代碼,但我想這只是一個非常簡單的例子。很高興能更深入地瞭解這裏發生的事情,並提供大量幫助。 – scruffyDog