【发布时间】:2023-03-13 00:50:01
【问题描述】:
如何在 Jasmine 单元测试中模拟或模拟窗口滚动和/或设置 window.pageYOffset 属性?
我正在使用 Angular 1.3、Jasmine 2.1 + Karma 0.12.28 和 PhantomJS 1.9.12
这是我的指令:
'use strict';
(function () {
angular
.module('myApp')
.directive('scrollNews', scrollNews);
function scrollNews(){
var directive = {
restrict: 'A',
scope: false,
link: link
};
return directive;
function link(scope, element) {
scope.limit = 2;
//add one to the limit
scope.loadMore = function() {
scope.limit += 1;
};
var raw = element[0];
angular.element(window).on('scroll', function () {
var scrollFrontier = this.pageYOffset + 800;
// when scrollFrontier has reached raw.scrollHeight, run loadMore()
if (scrollFrontier >= raw.scrollHeight) {
scope.loadMore(); // run the function
scope.$digest(); // update the HTML
}
});
}
}
})();
这是我的测试规范:
describe('Directive: scroll news', function(){
var element, $scope, $window;
beforeEach(module('myApp'));
beforeEach(inject(function($compile, $rootScope, _$window_){
$scope = $rootScope;
$window = _$window_;
element = angular.element('<div scroll-news></div>');
$compile(element)($scope);
$scope.$digest();
}));
it('should have a limit of 2 when no scrolling have occurred', function(){
expect($scope.limit).toBe(2);
});
it('should add one to the limit with loadMore function', function(){
$scope.loadMore();
expect($scope.limit).toBe(3);
});
it('should run loadMore() when scrolling has reached a specific height', function(){
element.scrollHeight = 1400;
var spy = spyOn($window, 'scrollTo');
$window.scrollTo(0, 1400);
expect(spy).toHaveBeenCalled();
expect($scope.limit).toBe(3); // Logs: Expected 2 to be 3. - so loadMore() have not called
});
});
我想模拟或模拟 element.scrollHeight 的窗口滚动事件,因为如果这两个达到相同的高度,我的指令将运行 loadMore() 函数。但是我怎样才能对它进行单元测试呢?
顺便说一句,该指令在生产中运行良好:)
【问题讨论】:
-
看起来使用
window.document.body.scrollTop = 1234有效:How to scroll a page with phantomJs -
似乎不起作用:(
标签: angularjs unit-testing jasmine phantomjs karma-runner