假设file1.js有一个名为doSomething()的函数,它可以动态加载file2.js
file2.js设置全局变量window.FILE2_LOADED == true
我如何编写如下的测试?
describe("A Unit Test", function() {
it("can I load scripts dynamically here?", function() {
loadScript('base/file2.js');
waitForDynamicallyLoadedScriptsToLoad_IWishThisFunctionExisted(function(){
expect(window.FILE2_LOADED).equal(true);
});
});
});
更新: 我找到了一些我仍然不喜欢的解决方案(并且没有解决方案),但认为值得记录。
这是在这个Github回购(它使用摩卡,而不是茉莉花) - > https://github.com/tonylampada/AngularJS-Testing-Article
您可以使用grunt test:unit
相关代码位于 dynamic_load_test.js
中describe("Unit: dynamic loading scripts", function() {
it("method 1 works, but using setTimeout and done is still ugly"+
"also, it may interfere with other tests", function(done) {
console.log('----------- method 1 -------------');
window.ACOUNTER = undefined;
loadScript('base/app/scripts/file2.js');
setTimeout(function(){
console.log('m1_2: '+window.ACOUNTER);
expect(window.ACOUNTER).equal(1);
done()
}, 1000)
console.log('m1_1: '+window.ACOUNTER);
});
it("method 2 works too, but I don't wanna have acces to the callback", function() {
window.ACOUNTER = undefined;
console.log('----------- method 2 -------------');
loadScript('base/app/scripts/file2.js', function(){
console.log('m2_2: '+window.ACOUNTER);
expect(window.ACOUNTER).equal(1);
});
console.log('m2_1: '+window.ACOUNTER);
});
it("method 3, doesn't work", function() {
window.ACOUNTER = undefined;
console.log('----------- method 3 -------------');
loadScript('base/app/scripts/file2.js');
describe("wait for all async to finish", function(){
it("now it will be loaded", function(){
console.log('m3_2: '+window.ACOUNTER);
expect(window.ACOUNTER).equal(1);
})
})
console.log('m3_1: '+window.ACOUNTER);
});
it("method 4, use jquery. Callback is never invoked.", function() {
window.ACOUNTER = undefined;
console.log('----------- method 4 -------------');
loadScript('base/app/scripts/file2.js');
$(document).ajaxStop(function () {
console.log('m4_2: '+window.ACOUNTER);
expect(window.ACOUNTER).equal(1);
});
console.log('m4_1: '+window.ACOUNTER);
});
});
答案 0 :(得分:1)
Jasmine支持异步测试:https://jasmine.github.io/2.0/introduction.html#section-Asynchronous_Support
我还可以通过函数的参数来设置要加载的文件的路径,这样就可以加载一些简单的模拟文件而不是整个(假设需要一些其他依赖项)脚本。