![](/img/trans.png)
[英]Asynchronous operations on Mongo trap: how can I perform kind of synchronously, I have correct logic
[英]How can I write tests that have setup and teardown operations that are asynchronous?
我正在使用執行一些異步操作的庫(pouchDB)。 為簡單起見,我將其中的細節排除在外,因為我認為這是涉及異步操作的“單元測試”的一個普遍問題(用引號引起來的單元測試是因為如果我正在測試集成,這並不是真正的單元測試。但是,使用QUnit似乎是為其編寫測試的最合適方法)。
我正在使用QUnit進行js單元測試。 我有兩個測試。 我發現,如果我運行任何一個(同時將另一個注釋掉),它們都會通過。 如果我將它們同時運行,則第二次運行將失敗。 似乎第二個程序正在運行,而第一個程序的拆卸已完成,這阻止了第二個程序的安裝成功完成。
module("pouchDB integration specs", {
setup: function(){
//some setup stuff
}
},
teardown: function(){
//some teardown stuff
});
}
});
asyncTest("test1", 1, function(){
test1MethodBeingTested();
document.addEventListener("completedTest1Stuff", function(){
deepEqual(newFriendSchedule, 'new', "Test 1 Looks Good'");
start();
});
});
});
asyncTest("test2", 2, function(){
stuffBeingTestedForTest2();
document.addEventListener("test 2 stuff done", function(){
deepEqual(expectedTest2Result, actualTest1Result, "test 2 looks good!");
start();
})
});
(為垃圾縮進而道歉。無論我怎么努力,SO的編輯都不喜歡我)
我看了馬丁·福勒 ( Martin Fowler)對異步代碼進行測試的經歷,但是我從中得到的收獲是“您應該設計代碼,使其本質上不異步”。 這無濟於事,因為我正在測試與不想修改的庫的集成(我也不認為我必須這樣做-確實已經解決了此問題?)
與測試方法類似,您可以在拆卸代碼中使用stop
和start
來暫停測試運行程序,直到完成清理代碼為止( asyncTest
進行隱式調用stop
)。 QUnit使用計數信號量進行stop
/ start
調用,因此,如果您有多個異步任務,則可以多次調用stop
。
快速示例:
var teardownDone = false;
var tests = 0;
var testContent = function() {
if (tests > 0) {
QUnit.ok(teardownDone);
} else {
QUnit.ok(true);
tests++;
}
};
module('example', {
teardown: function () {
// Without this call and the subsequent start(), tests will fail.
stop();
setTimeout(function () {
teardownDone = true;
start();
}, 1000);
}
});
test('test1', testContent);
test('test2', testContent);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.