1

我有一個指令,它看起來像這樣:

angular.module('myApp', []) 
    .directive('myDirective', ['$window', function($window){ 
    return { 
     link: function(scope, element, attr, controller) { 

      var w = angular.element($window); 
      function adjustTop(){ 
       var oldtop = scope.top; 
       if(oldtop<15){ 
        scope.top += 2; 
       }else{ 
        scope.top = 0; 
       } 
      } 

      w.bind('scroll', function() { 
       adjustTop(); 
      }); 

     } 
    }; 
}]); 

我如何可以模擬在單元測試scope.top價值?

回答

1

您可以簡單地使用$compile編譯該指令,並將其傳遞給您指定top屬性的範圍。要使用scroll事件測試scope.top的更改,可以使用JQLite的triggerHandler()功能。

DEMO

單元測試

describe('myDirective', function() { 

    var element, scope; 

    beforeEach(module('myApp')); 

    beforeEach(inject(function($compile, $rootScope) { 
    scope = $rootScope.$new(); 
    scope.top = 10; 
    element = $compile('<div my-directive></div>')(scope); 
    })); 

    it('should change the scope value when scrolling', inject(function($window) { 
    var jqWindow = angular.element($window); 
    jqWindow.triggerHandler('scroll'); 
    expect(scope.top).toBe(12); 
    jqWindow.triggerHandler('scroll'); 
    expect(scope.top).toBe(14); 
    jqWindow.triggerHandler('scroll'); 
    expect(scope.top).toBe(16); 
    jqWindow.triggerHandler('scroll'); 
    expect(scope.top).toBe(0); 
    })); 

}); 

注意:您綁定事件中添加scope.$apply()到例如通知角的上下文的角度,你已經更改範圍值。

w.bind('scroll', function() { 
    adjustTop(); 
    scope.$apply(); 
}); 
+0

如果指令沒有templateUrl您需要編譯一個html文件來獲取範圍嗎? – Winnemucca