2015-02-06 35 views
0

我有一個指令,可以動態地將加載指標添加到html元素。這裏是指令:將模板附加到元素的測試指令

return { 
    restrict: 'EA', 
    scope: true, 
    replace: true, 
    transclude: true, 
    template: '<div ng-transclude></div>', 
    link: function(scope, element, attr) { 
     var loadingExpression = attr["loadingIndicator"] || attr["loadingState"]; 

     scope.$watch(loadingExpression, function (isLoading) { 
      scope["isLoading"] = isLoading; 
     }); 

     $templateRequest('/templates/loading-indicator/indicator.html').then(function(template) { 
      $compile(template)(scope).appendTo(element); 
     }); 

     // Apply position:relative to parent element if necessary 
     var position = element.css('position'); 
     if (!position || position === 'static') { 
      element.css('position','relative'); 
     } 
    } 
}; 

按預期工作。

現在我想要寫一個簡單的測試了該指令,看是否正在加載的旋轉(在indicator.html模板的一部分)被添加到DOM:

describe('loadingIndicatorDirective', function() { 
    var element, $scope; 

    beforeEach(function() { 
     module('loadingIndicator'); 

     inject(function ($rootScope, $compile) { 
      element = angular.element(
       '<div>' + 
        '<div loading-indicator="true">' + 
         '<p>Lorem Ipsum ...</p>' + 
         '<p>TEST TEST TEST</p>' + 
        '</div>' + 
       '</div>' 
      ); 

      $scope = $rootScope; 
      $compile(element)($scope); 
      $scope.$digest(); 
     }) 
    }); 

    it('should create a loading spinner', function() { 
     var spinner = element.find('.loading-indicator'); 

     expect(spinner.length).toBe(1); 
    }); 
}); 

運行測試時,我得到錯誤:「錯誤:意外的請求:GET /templates/loading-indicator/indicator.html」。 我想要一個測試,它使用我在指令中附加的實際模板。這不可能嗎?

+0

好像你需要申請測試該模板了。我猜是注入'$ templateRequest',並從那裏採取。 – dcodesmith 2015-02-06 11:08:12

回答

1

這是因爲角試圖獲取HTML內容與HTTP GET請求。但是,在單元測試環境中,您實際上無法發出HTTP請求,因爲您沒有完整的Web服務器環境。

爲了解決這個問題,你必須避免直接的GET請求,並與預處理器,將編譯模板角成JavaScript字符串替換它們。例如,html2js完成這項工作。

您可以按照這些html2js的一個操作方法:

其他StackOverflow的用戶已經與html2js一些錯誤。您還可以檢查這些問題: