[英]How do I run a function before each test when using qUnit?
qUnit 的 nUnits [SetUp]
屬性的等價物是什么?
var mySetupFunc(details){/* setup code */}
QUnit.testStart(mySetupFunc);
從 QUnit 1.10.0pre-A 版本開始,每個注冊的回調都會收到一個哈希值作為第一個(也是唯一的)參數。 我在上面的例子中命名了我的“細節”。 散列的內容因回調而異。 這是每個散列中的信息列表。
開始
(所有測試開始)
{} /* empty hash */
完畢
(所有測試結束)
日志
(在 ok() 方法等中調用)
測試開始
(在每次測試開始時調用)
測試完成
(在每次測試結束時調用)
模塊開始
(在每個模塊開始時調用)
模塊完成
(在每次測試結束時調用)
// There's probably a more elegant way of doing this,
// but these two methods will add a row to a table for each test showing how long
// each test took.
var profileStartTime = null;
function startTimer(details) {
profileStartTime = new Date();
}
function stopTimer(details) {
var stopDate = new Date();
var duration = stopDate - profileStartTime;
jQuery('#profiling').append(
"<tr><td>"
+ (details.module ? details.module + ":" : "")
+ details.name
+ "<\/td><td class='duration'>"
+ duration
+ "<\/td><\/tr>");
}
QUnit.testStart(startTimer);
QUnit.testDone(stopTimer);
我上面引用的 html 表如下所示:
<div style='margin: 10px 0;'>
<table summary='profiling' class='profiling_table'>
<thead>
<tr>
<th>Test Name</th>
<th>Duration</th>
</tr>
</thead>
<tbody id='profiling'>
</tbody>
</table>
</div>
Perry Tew 的回答極大地幫助了我為自己解決這個問題,如果有人感興趣,我編寫了一個封裝的事件對象,它將設置所有事件供您使用。 見下文:
請注意, console.log()
不適用於所有瀏覽器!
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/jquery-ui.min.js"></script>
<script src="lib/qunit-1.9.0.js"></script>
<script src="lib/jquery.mockjax.js"></script>
<!-- QUnit Events -->
<script>
var testSetup = {
begin : function (data) /* before any tests start */ {
console.log("begin: [" + new Date().toLocaleTimeString() + "]");
},
moduleStart : function (data) /* before the start of each module */ {
console.log("-------\n moduleStart:", data.name);
},
testStart : function (data) /* before the start of each test */ {
console.log(" testStart:", data.name);
},
log : function (data) /* called after every assertion */ {
console.log(" log:", data.message);
},
testDone : function (data) /* after each test */ {
console.log(" testDone:", data);
},
moduleDone : function (data) /* after each module */ {
console.log(" moduleDone:", data);
},
done : function (data) /* all tests done */ {
console.log("done:", data);
},
init : function () {
QUnit.begin = testSetup.begin;
QUnit.moduleStart = testSetup.moduleStart;
QUnit.testStart = testSetup.testStart;
QUnit.log = testSetup.log;
QUnit.testDone = testSetup.testDone;
QUnit.moduleDone = testSetup.moduleDone;
QUnit.done = testSetup.done;
console.log("\n======== QUnit events initialized ==========");
}
};
$(document).ready(testSetup.init);
</script>
每當新的斷言測試批次開始運行時,就會調用
QUnit.testStart(name)
。name
是測試批次的字符串名稱。
有關更多信息,請參閱文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.