lundi 19 septembre 2016

Unit test controller

I make an ionic app and it finish but when i start to add tests to it I face a problem with $resources ,in this case I have this Controller :

  .controller('newAccountCtrl', function($scope, $window, $rootScope, API, $ionicPopup, $state) {
    $scope.newData = {};
    $scope.$on('$ionicView.enter', function() {

        $scope.newData = {};
    });
    $scope.newInfo = function() {
        API.newAccountInfo().update({ restCode: $scope.newData.restore_code }, $scope.newData, function(res, header) {
            $rootScope.popup('success', "OKAY");
            $window.location.href = '#/login';
        }, function(err) {
            if (err.data == null)
                $rootScope.popup("Error", "no connection");
            else
                $rootScope.popup('error', err.data.error);
        });
    }
})

and in the service i make a request using $resources in function :

angular.module('starter.services', [])
.factory('API', function($rootScope, $resource, $ionicPopup, $ionicLoading, $window) { return {
          newAccountInfo: function() {
            return $resource(base + '/restoreinfo/:restCode', { restCode: '@_restCode' }, {
                update: {
                    method: 'PUT'
                }
            }, {
                stripTrailingSlashes: false
            });
        }}});

and in the my test the following code:

describe('newAccountCtrl', function() {

var controller,
    deferredLogup, scope, $q;
beforeEach(angular.mock.module('starter'));
// TODO: Load the App Module
beforeEach(module('starter.controllers'));
beforeEach(module('starter.services'));

// TODO: Instantiate the Controller and Mocks
beforeEach(inject(function($controller, _$q_, $rootScope, _API_) {
    $q = _$q_;
    scope = $rootScope.$new();
    API = _API_;

    spyOn(API, 'newAccountInfo').and.callThrough(function(callback) {
        deferredLogup.promise.then(callback);
        return { $promise: deferredLogup.promise };
    });

    controller = $controller('newAccountCtrl', {
        '$scope': scope,
        API: API
    });

}));
it('#newAccountInfo', function() {

    scope.newInfo();

    expect(API.newAccountInfo.update).toHaveBeenCalled();

})   });

but I get the error :

Expected a spy, but got undefined.

What I misunderstand here, the code work perfect

Aucun commentaire:

Enregistrer un commentaire