dimanche 3 avril 2016

Testing factory function with jasmine using karma

I have a factory method, that makes call to the backend and return promise, on success of the http call the function return the value, and on error rejects the promise.

        function(){
          angular
                .module("module.name")
                .factory("landingPageDetails", landingPageDetails);


                landingPageDetails.$inject = ['$http', '$q', 'urlConfigs'];

                function landingPageDetails($http, $q, urlConfigs){
                  var service;

                  service = {
                    getLandingPageDetails: getLandingPageDetails
                  };

                  return service;

                  ///////////////

                  function getLandingPageDetails(){
                    return $http({
                      method: 'GET',
                      url: urlConfigs.landingPageDetails,
                    }).then(function(value, responseHeaders){
                       return value.data;
                    }).catch(function(){
                      $q.reject();
                    })
                  }

                }
        })();

      and the test case is 

     'use strict';

    describe('landingPageDetails', function(){
       var service, $httpBackend, urlConfigs, $q, $rootScope;

       beforeEach(module("moduleName"));
       beforeEach(module("modulename"));

       beforeEach(inject(function(_landingPageDetails_, _$httpBackend_, _urlConfigs_, _$q_, _$rootScope_){
          service = _landingPageDetails_;
          $httpBackend = _$httpBackend_;
          urlConfigs = _urlConfigs_;
          $q = _$q_;
          $rootScope = _$rootScope_;
          installPromiseMatchers();
       }))

       describe("#landingPageDetails", function(){

          var request, result;

          beforeEach(function(){
            var deferred = $q.defer();
            spyOn(service, 'getLandingPageDetails').and.returnValue(deferred.promise);
            request = $httpBackend.expectGET('***URI***').respond();
            result  = service.getLandingPageDetails();
          });

          it('makes the request', function () {
            $httpBackend.verifyNoOutstandingExpectation();
          });


          it("function called", function(){
            expect(service.getLandingPageDetails).toHaveBeenCalled();
          });

          describe("with the valid state", function(){
            beforeEach(function(){
              request.respond( {test: 'test'} );
              $httpBackend.flush();

            })

            it("resolved the promise with the data", function(){
              expect(result).toBeResolvedWith( {test: 'test'} );
            });

          });



       })

    });

running with karma, gives Error: Unsatisfied requests: GET ***URI**** TypeError: 'undefined' is not an object (evaluating 'request.respond') URI is the url to the api call

Aucun commentaire:

Enregistrer un commentaire