Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test AngularJS Directive with scrolling

I have an infinite scroll directive that I am trying to unit test. Currently I have this:

describe('Infinite Scroll', function(){
  var $compile, $scope;

  beforeEach(module('nag.infiniteScroll'));

  beforeEach(inject(function($injector) {
    $scope = $injector.get('$rootScope');
    $compile = $injector.get('$compile');

    $scope.scrolled = false;
    $scope.test = function() {
      $scope.scrolled = true;
    };
  }));

  var setupElement = function(scope) {
    var element = $compile('<div><div id="test" style="height:50px; width: 50px;overflow: auto" nag-infinite-scroll="test()">a<br><br><br>c<br><br><br><br>e<br><br>v<br><br>f<br><br>g<br><br>m<br>f<br><br>y<br></div></div>')(scope);
    scope.$digest();
    return element;
  }

  it('should have proper initial structure', function() {
    var element = setupElement($scope);

    element.find('#test').scrollTop(10000);

    expect($scope.scrolled).toBe(true);
  });
});

However the .scrollTop(10000); does not seem to trigger anything.

Is there anyway to unit test this type of functionality (I am able to unit test other directives with similar interactions like clicking on elements)?

In case it is relative, this is the infinite scroll code:

angular.module('nag.infiniteScroll', [])
.directive('nagInfiniteScroll', [
  function() {
    return function(scope, elm, attr) {
      var raw = elm[0];

      elm.bind('scroll', function() {
        if (raw.scrollTop + raw.offsetHeight >= raw.scrollHeight) {
          scope.$apply(attr.nagInfiniteScroll);
        }
      });
    };
  }
]);
like image 331
ryanzec Avatar asked May 14 '13 12:05

ryanzec


1 Answers

You have to trigger the scroll event on your element manually in your test:

element.find('#test').scrollTop(10000);
element.find('#test').triggerHandler('scroll');
like image 151
Andreas Köberle Avatar answered Oct 27 '22 00:10

Andreas Köberle