使用业力测试茉莉花的工厂功能

时间:2016-04-03 19:20:29

标签: angularjs unit-testing karma-jasmine

我有一个工厂方法,它调用后端并返回promise,在http调用成功时函数返回值,并在出错时拒绝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'} );
            });

          });



       })

    });

与业力一起运行,给出 错误:不满意的请求:GET *** URI **** TypeError:'undefined'不是对象(评估'request.respond') URI是api调用的URL

0 个答案:

没有答案