mercredi 18 novembre 2015

How can I Unit Test Rest Angular Service and Controller?

angular for Api Calling .

My Aim to Write a Unit test Case by calling Controller and Test all the Scope are assigned,the Code blocks of with REST API Response But not MOCK RESPONSE.

Rest Angular Service :-

(function () {

    angular.module('movieApp').service('movieApiService', callMoviesApi);

    function callMoviesApi(Restangular) {
        this.getMyMovie= function (Id) {
            return  Restangular.one('movies/' + movieId).get().then(function(result){
                return result.plain();
            });
        };

        this.getMoviesList = function () {
            return Restangular.all('movies').getList().then(function(result){
              return result.plain();
            });
        };
    }

}());

Where I am Injecting this Service to Controller as a Dependency Controller Code Follows :-

angular.module('movieApp').controller('MoviesController', ['$scope','movieApiService', function ($scope, MovieService) {

    $scope.movie = $stateParams.movieId;

    MovieService.getMovieDetails($scope.movie).then(function (result) {
        $scope.movieDetails = result;
        $scope.movieId = result._id;
        $scope.movieName = result.displayName;
    });
}
]);

I did tried to Write a Unit test for the Above Controller not Going good :-(

Test Code Follows:-

'use strict';

(function() {
    describe('MoviesController', function() {
        //Initialize global variables
        var scope,stateParams={},
            MoviesController;

        // Load the main application module
        beforeEach(module('movieApp'));

        beforeEach(inject(function($controller, $rootScope,$stateParams) {
            scope = $rootScope.$new();

            stateParams.movieId='Baahubali';

            HomeController = $controller('MoviesController', {
                $scope: scope,
                $stateParams:stateParams
            });
        }));

    it('Should call movieApi and Assign Scopes', function() {
          var Api="http://ift.tt/211IH17";
          var myScope=$httpBackend.expectGET(Api).passthrough(); 
           expect(scope.movie).toBeDefined();
            console.log('****'+scope.movie.displayName);

            });
        });
    })();

Error is Raising :-

Error: Unexpected request: GET http://ift.tt/1j7iKuQ
        Expected GET http://ift.tt/1j7iKuQ? 
            at $httpBackend (C:/wrokingdir2015/public/lib/angular-mocks/angular-mocks.js:1245)
            at sendReq (C:/wrokingdir2015/public/lib/angular-mocks/public/lib/angular/angular.js:9695)

Could Any One help me to Write a Unit test case Which can Initialize controller and Assing Scopes like in real controller for testing .

Honestly iam Pretty New Guy for Unit testing . Help Would Be Appreciated Greatly.

Aucun commentaire:

Enregistrer un commentaire