如何模拟指令$ scope变量?

时间:2015-04-12 13:29:54

标签: angularjs unit-testing angularjs-scope jasmine karma-jasmine

我的指令看起来像这样:

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 个答案:

答案 0 :(得分:3)

您可以简单地使用$compile来编译指令,并将其传递给您为其分配top属性的作用域。要使用scope.top事件测试scroll的更改,您可以使用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);
  }));

});

注意:在bind事件中添加scope.$apply()以通知角度您已在角度的上下文中进行了更改,例如范围值。

w.bind('scroll', function () {
  adjustTop();
  scope.$apply();
});
相关问题