2015-09-04 75 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

謝謝你的想法!太糟糕了,沒有更多的解決方案。 –