問題描述
我使用 jasmine 運(yùn)行并等待測試異步操作.一切正常,但我不太確定幕后發(fā)生了什么.
I use jasmine runs and wait to test asynchronous operations. Everything works fine but I'm not quite sure what goes on behind the scenes.
jasmine 文檔說明了以下示例,我在其中添加了三個(gè)日志語句.
The jasmine documentation states the following example to which I added three log statement.
describe("Asynchronous specs", function() {
var value, flag;
it("should support async execution of test preparation and exepectations", function() {
runs(function() {
flag = false;
value = 0;
setTimeout(function() {
flag = true;
}, 500);
});
waitsFor(function() {
value++;
if(flag) {
console.log("A");
}
return flag;
}, "The Value should be incremented", 750);
console.log("B");
runs(function() {
console.log("C");
expect(value).toBeGreaterThan(0);
});
});
});
});
第一個(gè) runs
和 waitsFor
對我來說非常清楚.Runs
啟動異步操作,waitsFor
等待條件.
The first runs
and waitsFor
are perfectly clear to me. Runs
starts an asynchronous operation and waitsFor
waits for a condition.
但是我不明白為什么第二個(gè) runs
直到 waitsFor
完成才開始.waitsFor
不是阻塞調(diào)用.
However I do not understand why the second runs
does not start until the waitsFor
is finished. The waitsFor
is not a blocking call.
我的猜測是 waitsFor
會隱式阻止任何后續(xù)的 runs
調(diào)用,直到它完成.是這樣嗎?
My guess is that waitsFor
implicitly blocks any following runs
call until it is finished. Is this so?
我的證據(jù)是 console.log 語句輸出:
My evidence is that the console.log statements output:
B A C
但如果 waitsFor
真的會阻塞它應(yīng)該是
But if waitsFor
would really block it should be
A B C
推薦答案
waitsFor
會阻塞,直到它等待的條件滿足或超時(shí).
waitsFor
does block until the conditions it's waiting for are met or it times out.
來自 jasmine 文檔:waitsFor() 提供了一個(gè)更好的接口,用于暫停你的規(guī)范,直到完成其他一些工作.Jasmine 將等到提供的函數(shù)返回 true,然后再繼續(xù)下一個(gè)塊.".
From the jasmine docs: "waitsFor() provides a better interface for pausing your spec until some other work has completed. Jasmine will wait until the provided function returns true before continuing with the next block.".
鏈接的文檔也有一個(gè)更清晰的示例或 waitsFor
.
The linked docs also have a slightly clearer example or waitsFor
.
編輯:啊,我明白你的意思了.waitsFor
不會阻塞未包含在 runs
、waitsFor
等中的 JS.
EDIT: Ah I see what you mean now. waitsFor
won't block JS that isn't wrapped in runs
, waitsFor
, ect.
jasmine 正在做的是獲取通過 runs
或 waitsFor
傳遞給它的函數(shù),如果 jasmine 當(dāng)前沒有等待,它會立即執(zhí)行該函數(shù).如果它正在等待,它在等待完成之前不會調(diào)用它.
What jasmine is doing is taking the function passed to it via runs
or waitsFor
and if jasmine is not currently waiting, it executes the function immediately. If it is waiting, it doesn't call it until it's finished waiting.
這不會停止 console.log
,因?yàn)樗驯粋鬟f給 jasmine,因此 jasmine 無法阻止它立即執(zhí)行.
That doesn't stop the console.log
as it's been passed to jasmine so jasmine can't prevent it from being executed straight away.
這篇關(guān)于jasmine 運(yùn)行和等待實(shí)際上是做什么的?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!