AngularJS:测试外部脚本是否被有效加载

时间:2013-05-07 17:55:09

标签: javascript unit-testing testing angularjs

我正在使用外部脚本(来自http://segment.io),我正在编写一个AngularJS模块来与之交互。

我想知道如何有效地测试他们的脚本是否已加载(除了运行真正的应用程序)。

我应该写一个end2end测试吗?

感谢您的帮助!

// Service is a factory
service.load = function(apiKey) {
    // Create an async script element for analytics.js.
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.async = true;
    script.src = ('https:' === document.location.protocol ? 'https://' : 'http://') +
        'd2dq2ahtl5zl1z.cloudfront.net/analytics.js/v1/' + apiKey + '/analytics.js';

    // Find the first script element on the page and insert our script next to it.
    var firstScript = document.getElementsByTagName('script')[0];
    firstScript.parentNode.insertBefore(script, firstScript);
};

2 个答案:

答案 0 :(得分:1)

如果文件留下全局,你可以简单地查找window.whatever看它是否已加载。

我使用的一个非常灵活的跨浏览器模式就是我称之为sentinal。在执行自定义代码之前,使用包装函数等待依赖关系到达。

例如,如果我动态地将jQuery注入到页面中,并且我知道其他动态需要它:

(function waiter(){
  if(!window.jQuery){ return setTimeout(waiter, 37); }

  $("#myDiv").fadeOut();

}())

此模式独立于任何脚本加载器或特定于浏览器的事件,并且不需要修改依赖文件,非常适合等待CDN的库副本。

您可以使用现代Array方法轻松扩展等待多个依赖项的概念:

(function waiter(){
  if(![ 
       window.jQuery,            // core
       window.jQuery.fn.effect,  // jq ui
       window.jQuery.fn.whizBang // jq ui plugin

   ].every(Boolean)){ return setTimeout(waiter, 37); }

  $("#myDiv").whizBang();

}())

答案 1 :(得分:0)

AngularJS IRC频道上有人指出我使用Jasmine等待阻止的工作解决方案:github.com/pivotal/jasmine/wiki/Asynchronous-specs

以下规格以下规格:

it('should load the API when called with api key', inject(function ($window, segmentio) {
        segmentio.load(apiKey);

        waitsFor(function() {
            return $window.analytics.initialized == true;
        }, "Segmentio never loaded", 10000);

        runs(function () {
            expect($window.analytics).toBeDefined();
            expect($window.analytics.initialized).toBeTruthy();
            // Unload
            $window.analytics = null;
        });
    }));
相关问题