2

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.

Adithya Puram
  • 303
  • 2
  • 6
  • 23

1 Answers1

1

To get the offsetHeight of an element, it needs to be on the page, so you need to attach it to the document:

it("should call sizeChanged method", function () {
    element[0].style.height = '10px';

    $compile(element)($scope);
    angular.element($document[0].body).append(element);
    $scope.$apply();

    expect($scope.sizeChanged).toHaveBeenCalled();
});

By the way, offsetHeight is read-only property so use style.height. For more info: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetHeight

This post helped me find the answer: Set element height in PhantomJS

Community
  • 1
  • 1
pedroto
  • 643
  • 1
  • 6
  • 9