如何使用滚动测试AngularJS指令 [英] How to test AngularJS Directive with scrolling

查看:111
本文介绍了如何使用滚动测试AngularJS指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个无限滚动指令,我试图进行单元测试。目前我有这个:

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);
  });
});

然而.scrollTop(10000);似乎没有触发任何东西。

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);
        }
      });
    };
  }
]);


推荐答案

您必须手动触发元素上的滚动事件在你的测试中:

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

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

这篇关于如何使用滚动测试AngularJS指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆