I am planning to unit test a angular directive using jasmine. My directive looks like this
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
);
}
};
});
My unit test case is as follows
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();
});
});
});
The code works fine. But the unit test fails. The watch function gets called but element[0].offsetHeight in watch always returns 0. How can we update the element so that watch can observe the new height. Is there a way to even test this, because we don't really have a DOM here. Please guide me on changes that need to be done with unit test.