我没有对事件进行大量测试,主要是业务逻辑,我正在尝试寻找测试浏览器调整大小事件等内容的示例。
有问题的代码如下。
ui.resized = function(c, t) {
var curr,
prev;
window.addEventListener('resize',
function() {
curr = ui.viewport();
if ( prev && curr != prev ) {
clearTimeout(t);
t = setTimeout(c, 50);
}
prev = curr || prev;
}, false);
return c;
};
对此有什么想法吗?或者有人能给我指出正确的方向吗?
最佳答案
我在构建图表的指令中做了类似的事情。我希望每当调整窗口大小时都重新绘制图表,以便其适当缩放。该指令如下所示:
(function () {
'use strict';
angular.module('ad.common')
.directive('zxChart', chartDirective);
/** @ngInject */
function chartDirective($window, MyService) {
function link(scope, element, attrs) {
scope.id = attrs.id || 'default-id';
scope.width = attrs.width || $window.innerWidth - ($window.innerWidth * 0.1);
attrs.$set('id', scope.id);
angular.element($window).bind('resize', function () {
scope.width = attrs.width || $window.innerWidth - ($window.innerWidth * 0.1);
MyService.whenWindowIsResized(element[0], scope.width);
});
scope.$watch('chartData', function () {
MyService.drawChart(element[0], scope.width, scope.chartData);
});
}
return {
restrict: 'E',
replace: true,
template: '<div id="" class="my-chart"></div>',
scope: {
chartData: '=',
},
link: link
};
}
})();
我的测试分两部分完成,首先我测试绑定(bind)是否正确发生:
describe('Check binding to event', function () {
var $scope,
$compile,
stubWindow;
beforeEach(function () {
module('ad.common', function ($provide) {
stubWindow = {
addEventListener: sinonSandbox.stub()
};
$provide.value('$window', stubWindow);
});
inject(function ($injector) {
$scope = $injector.get('$rootScope').$new();
$compile = $injector.get('$compile');
});
});
it('should have added a resize event listener to $window', function () {
var element = angular.element('<zx-chart id="foo"></zx-chart>');
$compile(element)($scope);
$scope.$digest();
stubWindow.addEventListener.should.have.been.calledOnce;
stubWindow.addEventListener.should.have.been.calledWith("resize");
});
});
然后我测试触发调整大小事件是否会导致调用我希望在调整大小事件触发时触发的方法:
describe('Check call to event', function () {
var $scope,
$compile,
$window,
stubMyService;
beforeEach(function () {
module('ad.common', function ($provide) {
stubMyService = {
whenWindowIsResized: sinonSandbox.stub(),
};
$provide.value('MyService', stubMyService);
});
inject(function ($injector) {
$scope = $injector.get('$rootScope').$new();
$compile = $injector.get('$compile');
$window = $injector.get('$window');
});
});
it('a resize event should trigger a call to MyService.whenWindowIsResized', function () {
var element = angular.element('<zx-chart id="foo"></zx-chart>');
$compile(element)($scope);
$scope.$digest();
stubMyService.whenWindowIsResized.should.not.have.been.called;
angular.element($window).triggerHandler('resize');
stubMyService.whenWindowIsResized.should.have.been.calledOnce;
});
您当然需要提取调整大小调用中的功能,并将其放入服务中。但在我看来,这只会让测试变得更容易。
关于javascript - 为浏览器调整大小事件编写测试。 PhantomJS、Mocha、Chai 和 Sinon,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31307064/