2015-04-06 132 views
0

我有一個指令,它看起來像這樣:Angularjs單元測試隔離範圍值

angular.directive('myDirective', ['$compile', function($compile){ 
    return { 
     link: function(scope, element, attr, controller) { 
      function update(){ 
       if(scope.value == "A"){ 
        scope.desc = "Welcome"; 
       }else{ 
        scope.desc = "Not Welcome"; 
       } 
      } 

      scope.$watch('value', function(newValue, oldValue) { 
       update(); 
      },true); 

      update(); 
     } 
    }; 
}]); 

我如何寫一個單元測試,可以驗證scope.value的變化將返回正確的scope.desc?基於

回答

2

的信息從this question

// inject $rootScope and $compile in beforeEach 
it('should change desc on value change', function() { 
    var scope = $rootScope.$new(); 
    var element = angular.element('<my-directive></my-directive>'); 
    element = $compile(element)(scope); 
    $rootScope.$digest(); 
    var directiveScope = element.scope(); 
    expect(directiveScope.desc).toEqual("Not Welcome"); 
    directiveScope.value = 'A'; 
    $rootScope.$digest(); 
    epxect(directiveScope.desc).toEqual("Welcome"); 
}); 

Fiddle