問題描述
我正在使用 phantomjs 運(yùn)行 jasmine 測試.我的 jasmine 測試在 describe 塊周圍使用 require 以確保加載所有正確的模塊.
I am using phantomjs to run jasmine test. My jasmine tests are using require around the describe blocks to ensure all the right modules are loaded.
我的測試無法運(yùn)行,因?yàn)?page.evaluate ->jasmine.getEnv().execute();
在 requirejs 完成加載模塊之前運(yùn)行.
My tests would not run because page.evaluate -> jasmine.getEnv().execute();
runs BEFORE requirejs finishes loading the modules.
我想知道是否有人知道解決此問題的真正好方法.我有一個答案,我將在下面發(fā)布,但很想通過其他答案比較筆記.如果你的更好,我會明確選擇它作為答案:)
I was wondering if anyone knows a real good way around this. I have an answer I'm going to post below but would love to compare notes via other answers. If yours is better, I will def pick it as answer obviously :)
推薦答案
我的解決方案,使用 jQuery,是這樣的:
My solution, with jQuery available, is this:
在您的任何測試運(yùn)行之前加載配置文件.
Load a config file before any of your tests run.
var jasmine_deferreds = [];
// Setup an event to fire on the document
// I actually did this with native code rather than jquery because
// I wanted to minimize jquery usage
// ....
// setTimeout so all files loaded after this will finish registering their requires
setTimeout( function() {
$.when.apply( null, jasmine_deferreds ).then( function() {
// Fire event that was created
});
}, 5 );
如何構(gòu)建延遲數(shù)組然后解決它們?nèi)Q于您.我基本上推到了數(shù)組,然后在要求完成后解決.我用我自己的版本包裝了 require ,它知道在完成后自動解決它 - 所以我不需要在每個測試中手動推送和解決.
It's up to you how you want to build up the array of deferreds and then resolve them. I essentially pushed to the array and then resolved when the require was done. I wrapped require with my own version that would know to resolve it upon completion automatically - so I don't need to push and resolve manually in each test.
然后在我的幻像文件中我這樣做:
Then in my phantom file I do this:
page.evaluate ->
mylistener = ( document ) -> jasmine.getEnv().execute();
document.addEventListener( 'test_ready_event', mylistener, false);
這使得我知道我所有的 require 模塊都被加載了,而沒有一些任意的 setTimeout
一旦我加載太多文件就可能太短了.我正在使用的 setTimeout
是安全的,因?yàn)樗鼉H用于在主調(diào)用堆棧完成后觸發(fā).它并不關(guān)心時間.
This makes it so I know all my require modules are loaded without having some arbitrary setTimeout
that could be too short once I am loading too many files. The one setTimeout
I'm using is safe because it's only being used to fire after main callstack is done. It doesn't really care about the time.
這篇關(guān)于如何可靠地執(zhí)行通過 phantomjs 使用 requirejs 的 Jasmine 測試?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!