vendredi 1 mai 2015

Unit test in angularJs with Jasmine: mock an infinite recursive function

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?

Aucun commentaire:

Enregistrer un commentaire