2
我打算單元測試使用茉莉花的角度指令。我的指令看起來像這樣單元測試angularjs指令與手錶元素高度
angular.module('xyz.directive').directive('sizeListener', function ($scope) {
return {
link: function(scope, element, attrs) {
scope.$watch(
function() {
return Math.max(element[0].offsetHeight, element[0].scrollHeight);
},
function(newValue, oldValue) {
$scope.sizeChanged(newValue);
},
true
);
}
};
});
我的單元測試情況如下
describe('Size listener directive', function() {
var $rootScope, $compile, $scope, element;
beforeEach(inject(function(_$rootScope_, _$compile_) {
$rootScope = _$rootScope_;
$compile = _$compile_;
$scope = $rootScope.$new();
element = angular.element('<span size-listener><p></p></span>');
$compile(element)($scope);
$scope.$digest();
}));
describe("Change in size", function() {
it("should call sizeChanged method", function() {
element[0].offsetHeight = 1;
$compile(element)($scope);
$scope.$digest();
$scope.$apply(function() {});
expect($scope.sizeChanged).toHaveBeenCalled();
});
});
});
的代碼工作正常。但單元測試失敗。手錶功能被調用,但手錶中的元素[0] .offsetHeight總是返回0.我們如何更新元素,以便手錶可以觀察新的高度。有沒有一種方法可以測試,因爲我們在這裏沒有真正的DOM。請指導我進行單元測試需要完成的更改。