mercredi 3 juin 2015

Mocking a dependent service to a controller unit test in AngularJS

I have a problem when unit testing an Ionic app. I have seen similar questions, but none solved my problem.

Basically, this is my controller.js

angular.module('starter.controllers')
.controller('myController', function($scope, myService) {

    $scope.test = function() {
        return myService.getTestVariable();
    };

});

and this is my service.js

angular.module('starter.services')
.factory('myService', function() {

    var self = this;
    self.testVariable = true;

    return {
        getTestVariable : function() {
            return self.testVariable;
        }
    };
});

Modules are created in a app.js file:

angular.module('starter', ['starter.controllers', 'starter.services']);           
angular.module('starter.services', []);
angular.module('starter.controllers', []);

Now, I want to test the controller and use a mock versione of the service, so I set up the test like this:

describe('Controller: myController', function() {
    var scope, controller, serviceMock;

    beforeEach(function() {
        module('starter');
    });

    beforeEach(function () {
        serviceMock= {
            getTestVariable : function() {return true;}
        };

        module(function ($provide) {
            $provide.value('myService', serviceMock);
        });
    });

    beforeEach(inject(function($rootScope, $controller) {
        scope = $rootScope.$new();
        controller = $controller('myController', {
            $scope: scope
        });
    }));

    it('should work as expected', function(){
        spyOn(serviceMock, 'getTestVariable').and.callThrough();
        scope.test();
        expect(serviceMock.getTestVariable).toHaveBeenCalled();
    });
});

However, when I try to run the test, it prints an error:

TypeError: 'undefined' is not a function (evaluating 'myService.getTestVariable()')
    at <dir>/controller.js:5

Why is this happening?

Aucun commentaire:

Enregistrer un commentaire