jeudi 24 septembre 2015

Test controller with service injection

I am currently testing my AngularJS application and I am struggling with the tests of the controllers injecting a service.

Here is my controller:

.controller('UserCtrl', ['$scope', '$routeParams', 'User', function ($scope, $routeParams, User) {

    $scope.hello = "lol";

    $scope.userId = $routeParams.id;
    var user = new User($scope.userId);

    $scope.load = function(){
        user.load().then(
            function(user){
                $scope.name     = user.name;
            },
            function() {
                $scope.dataFail = 'error error' ;
            }
        );
    };

    $scope.load();
}]);

Here is my User service (that i want to inject in my controller's test)

.factory('user', ['$http', '$q', function ($http, $q) {

var User = function (id) {
    this.id = id;
    this.name = null;
};

User.prototype.load = function () {
    var deferred = $q.defer();

    $http.post('/user/' + this.id + '/load')
        .success(function(data) {
            var user = new User(data.id);
            user.name = data.name
            deferred.resolve(user);
        })
        .error(function(err, code) {
            deferred.reject(err);
        $log.error(err, code);
    });
    return deferred.promise;
};

return User;

And finally is my test :

describe('Controller: UserCtrl', function () {

var $controller, $scope, User;

beforeEach(module('octosendApp', function($provide){
    User = jasmine.createSpyObj('User', ['load']);

    User.load.and.returnValue({
        name: 'testName'
    });
    $provide.value('User', User);
}));

beforeEach(inject(function(_$controller_, $rootScope, _User_){
    $scope = $rootScope.$new();
    User = _User_;

    $controller = _$controller_('UserCtrl', {
        $scope: $scope,
        User : User,
        $routeParams: {id: 2}
    });
}));

it('should have a hello property', function() {
    expect($scope.hello).toBeDefined();
});

});

I get the following error :

TypeError: '[object Object]' is not a constructor (evaluating 'new User($scope.userId)')

I guess the problem is because my factory is object oriented and i can not use the constructor. i followed this tutoarial : http://ift.tt/1iOgyZQ and did the exact same, the only difference is the structure of the factory, which I do NOT want to change.

Thank you for your help.

Aucun commentaire:

Enregistrer un commentaire