0

I'm trying to unit test with Jasmine a controller with an infinite recursive function that I call at the controller creation like this:

angular.module('myApp')
.controller('LargeHomeCtrl', ['$scope', '$timeout', 
    function ($scope, $timeout) {

    //some code to be tested

    function updateInfo () {
    //do some things
        $timeout(updateInfo(), 8000);
    }

    updateInfo();
}]);

But I can't inject this controller like the code below for unit-testing else I get this error:

WARN [PhantomJS 1.9.8 (Linux)]: Disconnected (1 times), because no message in 10000 ms.

beforeEach(inject(function ($controller, _$rootScope_) {
    spyOn($controller, 'updateInfo').and.returnValue(null);
    $scope = _$rootScope_;
    $ctrl = $controller('LargeHomeCtrl', {
        $scope: $scope
    });
}));

I don't see any other way that mock the function, but if I define it before my controller injection, I get an error (updateInfo() method does not exist) because the controller is not yet injected.

I try to mock my functon updateInfo() with spyOn like this:

spyOn($controller, 'updateInfo').and.returnValue(null);

I am missing something basic (I'm new to jasmine)? What could I do?

Simon
  • 6,025
  • 7
  • 46
  • 98
  • 1
    Are you sure you want such recursion there? Or you just want the `updateInfo` to be executed every 8 sec? I think you should remove extra function call from $timeout: `$timeout(updateInfo, 8000);` (removed parenthesis). This is not jasmine problem - Angular will have trouble instantiating this controller in application too. – fracz May 02 '15 at 10:06
  • You're right, in this special case, I can use setTimeout and it works fine, thanks! But I will maybe need to run a test later with a similar function, but, no, Angular seems not to have troubles instantiating this controller. – Simon May 03 '15 at 15:22
  • Yes, it does - see [this fiddle](http://jsfiddle.net/fracz/HB7LU/13406/) but be careful - your browser might freeze for some time. There is infinite recursion regardless of whether you start this controller in Jasmine or not. – fracz May 03 '15 at 19:30

0 Answers0