Unit test window resizing method

I have the following code in a simple directory link function that checks for window resizing and calls a function.

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

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

I am trying to check on ($window).on('resize')what is being called scope.getSize().

In my tests, I compile my directive like this:

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();
}));

Then I look through the window resizing function and expect the function to be 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 quite sure why this does not exist, is there something obvious that I'm doing wrong?

+4
source share
1 answer

if someone is stuck on something like this:

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();
});
+7
source

All Articles