如何使用滚动测试AngularJS指令

时间:2013-05-14 12:53:49

标签: testing angularjs jasmine

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

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);似乎没有触发任何东西。

是否有单元测试这种类型的功能(我能够通过点击元素对其他类似交互的其他指令进行单元测试)?

如果它是相对的,这是无限滚动码:

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

2 个答案:

答案 0 :(得分:7)

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

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

答案 1 :(得分:0)

最近有同样的问题。要使滚动起作用,您需要在body标签上设置一些尺寸,以便可以滚动窗口。

var scrollEvent = document.createEvent( 'CustomEvent' ); // MUST be 'CustomEvent'
scrollEvent.initCustomEvent( 'scroll', false, false, null );

var expectedLeft = 123;
var expectedTop = 456;

mockWindow.document.body.style.minHeight = '9000px';
mockWindow.document.body.style.minWidth = '9000px';
mockWindow.scrollTo( expectedLeft, expectedTop );
mockWindow.dispatchEvent( scrollEvent );

不幸的是,这在PhantomJS中不起作用

如果您在 Travis CI 上运行测试,您还可以使用Chrome ,将以下内容添加到.travis.yml

before_install:
   - export CHROME_BIN=chromium-browser
   - export DISPLAY=:99.0
   - sh -e /etc/init.d/xvfb start

在您的业力配置中自定义Chrome启动器:

module.exports = function(config) {
    var configuration = {

        // ... your default content

        // This is the new content for your travis-ci configuration test
        //  Custom launcher for Travis-CI
        customLaunchers: {
            Chrome_travis_ci: {
                base: 'Chrome',
                flags: ['--no-sandbox']
            }
        },

        // Continuous Integration mode
        // if true, it capture browsers, run tests and exit
        singleRun: true 
    };

    if(process.env.TRAVIS){
        configuration.browsers = ['Chrome_travis_ci'];
    }

    config.set( configuration );

};
相关问题