2015-09-04 72 views
0

我试图在我的AngularJS指令上构建一个单元测试,但我遇到了一些呈现模板的问题。具体而言,我的指令templateUrl的引用为window.STATIC_URL,根据环境是生产还是分段进行更改。在运行Karma测试时,收到错误:用Karma和动态模板URL测试AngularJS指令

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应用程序。该变量由settings.py中的Django的STATIC_URL变量设置。它指向我在生产中的S3路径,以及我在开发中的本地路径。

我已经试过

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

似乎工作的唯一方法是从指令的templateUrl中删除变量,并将其替换为我测试的环境的静态URL。但是,这并不理想,因为我希望它改变取决于在应用程序上。我很好地从测试中明确设置STATIC_URL,但不是Angular应用程序。

我在这一点上没有想法。如果有人遇到类似的事情,我会很感激帮助!谢谢。

回答

1

在过去,我已经采取了这种做法在我的指示使用动态模板网址:

<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; 
     } 
    }; 
}]); 

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

+0

谢谢你的想法!太糟糕了,没有更多的解决方案。 –