我想为指令编写单元测试,如下所示:
angular.module('myApp', [])
.directive('myDirective', ['$window','MyConfig', function($window,MyConfig){
return {
link: function(scope, element, attr, controller) {
var w = angular.element($window);
var top = 70;
function adjustTop(){
var oldtop = scope.top;
var newtop = top - w.scrollTop();
if(newtop>15){
scope.top = newtop;
}else{
scope.top = 15;
}
if(oldtop!=newtop){
scope.$apply();
}
}
if(MyConfig.adjusttop){
w.bind('scroll', function () {
adjustTop();
});
adjustTop();
}else{
scope.top = 15;
};
}
};
}]);
describe('myDirective:', function () {
it("should perform adjust top position only when MyConfig.adjusttop is true",function(){
// how to write the test here?
});
});
如果MyConfig.adjusttop
设置为true,我应该如何编写单位测试以确认最高位置?我可以使用spyOn
来检测有待调用的adjustTop()
函数吗?如果可以,如何使用它?
答案 0 :(得分:0)
你不能spyOn adjustTop因为它对链接功能是“私有的”。但是,您可以像预期的那样测试scope.top更改。
您需要执行以下操作:(不包括模块和依赖注入,详细信息可能因UT库而异,是否有jQuery,但在概念上......)
spyOn(MyConfig,'adjusttop').and.returnValue(true);
spyOn($window,'scrollTop').and.returnValue(0);
var element = angular.element("<my-directive></my-directive>");
$scope = $rootScope.$new(); // get a new $scope
$compile(element)($scope); // compile and link the directive
$scope.$digest();
$(window).trigger('scroll'); // to get the scroll event to actually fire
expect($scope.top).toBe(70); // assuming I did the math right???