Search code examples
angularjsunit-testingwindowkarma-jasmine

Unit test $window resize method


I have the following code in a simple directive link function which checks for a window resize and calls a function.

return {
    restrict: 'A',
    link: function (scope) {
        angular.element($window).on('resize', function() {
            scope.getSize();
        });

        scope.getSize() = function() {
            return true;
        };
    }
}

I'm trying to test on ($window).on('resize') that scope.getSize() is called.

In my tests I compile my directive like so:

beforeEach(inject(function($rootScope, $compile, _$window_) {
    $window = _$window_;
    $scope = $rootScope.$new();
    element = angular.element('<div data-watch-resize></div>');
    element = $compile(element)($scope);
    $scope.$digest();
}));

I then spy on the resize function of window, and expect the function to have been called

spyOn($window, 'resize');
$window.innerWidth = 1026;
$scope.$digest();
expect(element.scope().getSize()).toHaveBeenCalled();

however i get the following error

Error: resize() method does not exist

I'm not really sure why it doesn't exist, is there something obvious I am doing wrong?


Solution

  • if anyone gets stuck on something similar:

    it('should expect scope.getSize() to have been called on window resize', function () {
        spyOn(element.isolateScope(), 'getSize');
        $window.innerWidth = 1026;
        angular.element($window).triggerHandler('resize');
        $scope.$digest();
        expect(element.isolateScope().getSize).toHaveBeenCalled();
    });