【问题标题】:Testing AngularJS Directive with Karma & Dynamic Template URL使用 Karma 和动态模板 URL 测试 AngularJS 指令
【发布时间】:2015-09-04 23:54:07
【问题描述】:

我正在尝试在我的 AngularJS 指令上构建一个单元测试,但在渲染模板时遇到了一些障碍。具体来说,我的指令的templateUrl 有一个对window.STATIC_URL 的引用,它会根据环境是生产环境还是暂存环境而变化。运行 Karma 测试时,我收到错误:

Error: Unexpected request: GET undefinedjs/templates/myfolder/mytemplate.html。这是指令:

app.directive('myDirective', function(){
    ...
    templateUrl: window.STATIC_URL + 'js/templates/myfolder/mytemplate.html'
});

我正在使用 ng-html2js 来预处理所有 HTML 文件。这是业力配置:

// list of files / patterns to load in the browser
files: [
    'build/lib.min.js',
    'bower_components/angular-mocks/angular-mocks.js',
    'js/*.js',
    'js/**/*.js',
    'js/templates/**/*.html',
    'tests/*Spec.js'
],


preprocessors: {
  'js/templates/**/*.html': ['ng-html2js']
},

ngHtml2JsPreprocessor: {
  // setting this option will create only a single module that contains templates
  // from all the files, so you can load them all with module('templates')

  moduleName: 'templates'
},

测试运行var element = $compile("<my-directive></my-directive>")($rootScope);。我已将 compile、rootScope 以及 httpBackend 注入到我的测试中。

另外,模板是在注入器之前加载的:

beforeEach(module('my-app'));
beforeEach(angular.mock.module('templates'));

为什么我依赖 window.STATIC_URL

这是我对如何将不断变化的变量注入我的 Angular 应用程序的最佳猜测。该变量由 Django 的 STATIC_URL 变量在 settings.py 中设置。它指向我在生产中的 S3 路径,以及我在开发中的本地路径。

我的尝试

由于被调用的指令依赖于window.STATIC_URL,因此我尝试在我的测试中编辑 STATIC_URL。 (即window.STATIC_URL = '/static')这似乎不起作用。

似乎唯一可行的方法是从指令的 templateUrl 中删除变量,并将其替换为我正在测试的环境的静态 URL。但是,这并不理想,因为我希望它根据应用程序。我可以在测试中明确设置 STATIC_URL,但不能在 Angular 应用程序中设置。

我现在没有想法。如果有人遇到类似的情况,我将不胜感激!谢谢。

【问题讨论】:

    标签: angularjs django karma-runner


    【解决方案1】:

    过去我采用这种方法在我的指令中使用动态模板 url:

    <div data-your-directive data-template-url="'partials/other.html'"></div>
    

    将 url 作为可选属性传递,如果提供,它将覆盖默认值。在我的指令中,我有:

    angular.module('directives').directive('yourDirective', [function() {
        return {
            templateUrl: function($element, $attrs) {
                // Default template path.
                var templateUrl = 'partials/default.html';
    
                // Check if a template url attribute has been passed in to the 
                // directive. If one has been provided then make use of this
                // rather than the default.
                if ($attrs.templateUrl !== undefined) {
                    templateUrl = $attrs.templateUrl;
                }
    
                return templateUrl;
            }
        };
    }]);
    

    这种方法可能证明对您来说更容易测试。

    【讨论】:

    • 感谢您的想法!太糟糕了,没有更全面的解决方案。
    猜你喜欢
    • 2017-01-03
    • 2014-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    • 2014-07-12
    • 2014-05-04
    • 2016-06-24
    相关资源
    最近更新 更多