2015-02-06 61 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一些错误。您还可以检查这些问题: