問題描述
我不想花幾個(gè)小時(shí)閱讀代碼來找到相關(guān)部分,但我很好奇 jasmine 如何實(shí)現(xiàn)它的時(shí)鐘.它的有趣之處在于它可以使用同步測試代碼來測試異步代碼.AFAIK,使用當(dāng)前支持 ES5 的 node.js,這是不可能的(異步函數(shù)在 ES7 中定義).它是否使用 estraverse 之類的東西解析 js 代碼并從同步代碼構(gòu)建異步測試?
I don't want to read code for hours to find the relevant part, but I am curious how jasmine implements its clock. The interesting thing with it is that it can test async code with sync testing code. AFAIK, with the current node.js, which supports ES5, this is not possible (async functions are defined in ES7). Does it parse the js code with something like estraverse and build an async test from the sync one?
只是我所說的一個(gè)例子:
Just an example of what I am talking about:
it("can test async code with sync testing code", function () {
jasmine.clock().install();
var i = 0;
var asyncIncrease = function () {
setTimeout(function () {
++i;
}, 1);
};
expect(i).toBe(0);
asyncIncrease();
expect(i).toBe(0);
jasmine.clock().tick(2);
expect(i).toBe(1);
jasmine.clock().uninstall();
});
這里 expect(i).toBe(1);
應(yīng)該在回調(diào)中.
In here the expect(i).toBe(1);
should be in a callback.
推薦答案
install()
函數(shù)實(shí)際上將 setTimeout
替換為 jasmine 讓您可以更好地控制的模擬函數(shù).這使它同步,因?yàn)闆]有完成實(shí)際的等待.相反,您可以使用 tick()
函數(shù)手動(dòng)將其向前移動(dòng),該函數(shù)也是同步的.
The install()
function actually replaces setTimeout
with a mock function that jasmine gives you more control over. This makes it synchronous, because no actual waiting is done. Instead, you manually move it forward with the tick()
function, which is also synchronous.
查看源代碼:https://github.com/jasmine/jasmine/blob/ce9600a3f63f68fb75447eb10d62fe07da83d04d/src/core/Clock.js#L21
假設(shè)您有一個(gè)內(nèi)部設(shè)置超時(shí) 5 小時(shí)的函數(shù).Jasmine 只是替換了該 setTimeout
調(diào)用,以便在您調(diào)用 tick()
時(shí)調(diào)用回調(diào),以便內(nèi)部計(jì)數(shù)器達(dá)到或超過 5 小時(shí)標(biāo)記.很簡單!
Suppose you had a function that internally set a timeout of 5 hours. Jasmine just replaces that setTimeout
call so that the callback will be called when you call tick()
so that the internal counter reaches or exceeds the 5 hour mark. It's quite simple!
這篇關(guān)于茉莉花鐘的工作原理是什么?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!