【问题标题】:how to test an AngularJS service with rest calls in Jasmin如何在 Jasmin 中使用休息调用测试 AngularJS 服务
【发布时间】:2016-10-15 06:23:51
【问题描述】:

嘿,我是 AngularJS 测试的新手,我想弄清楚,

  1. 我应该如何测试负责我的休息调用的 AngularJS 服务。

  2. 如何在我要测试的其他控制器中调用此服务。

我需要测试使用休息请求的数据工厂服务 需要测试的代码是这样的:

var app = angular.module("app",[]);

app.controller("mainCTRL", ["$scope","dataFactory",function($scope,dataFactory){
  $scope.title = "Hello World";
  dataFactory.getEntries("fakeSuffix");
  
  }]);

app.factory('dataFactory', ['$http', '$window', '$log', function ($http, $window, $log) {
            var urlBase = $window.location.origin + '/api',
                dataFactory = {};
            /**
            * get all Entries.
            **/
            dataFactory.getEntries = function (suffix) {
                $log.debug("************ Get All Entries ************");
                $log.debug("url:", urlBase + suffix);
                return $http.get(urlBase + suffix, { headers: { cache: false } });
            };

            /**
            * get single Entry.
            **/
            dataFactory.getEntry = function (id) {
                $log.debug("************ Get Single Entry ************");
                return $http.get(urlBase + '/' + id);
            };

            /**
            * insert Entry
            **/
            dataFactory.postEntry = function (method, entry) {
                var url = urlBase + '/' + method;
                return $http.post(url, entry);

            };

            /**
            * update Entry
            **/
            dataFactory.updateEntry = function (entry) {
                $log.debug("************ Update Single Entry ************");
                return $http.put(urlBase + '/' + entry.id, entry);
            };

            /**
            * delete Entry
            **/
            dataFactory.deleteEntry = function (id) {
                $log.debug("************ Delete Single Entry ************");
                return $http.delete(urlBase + '/' + id);
            };

            return dataFactory;
        }]);
<script src="https://ajax.googleapis.com/ajax/libs/jQuery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div id="block" ng-app="app" ng-controller="mainCTRL">
{{title}}
</div>

【问题讨论】:

    标签: javascript angularjs rest mocking jasmine


    【解决方案1】:

    Q.1 - 我应该如何测试负责我的休息调用的 AngularJS 服务。
    Ans. - 我已经为您的以下服务方法之一。您可以为其他方法编写类似的测试用例。

    Q.2 - 如何在我想测试的其他控制器中调用此服务。
    Ans. - 在下面的代码中,就像你一样为依赖$httpgetpostputdelete 方法的服务编写测试用例,我在测试用例中注入了$httpBackend,并在@ 中模拟了所有这些方法987654327@ 块。同样,当您为依赖于该服务的控制器编写测试用例时,您将不得不使用类似的方法。只需在控制器的测试用例中注入服务并模拟将从控制器调用的服务的所有方法。

    //AngularJS Code
    
    var app = angular.module("app",[]);
    
    app.controller("mainCTRL", ["$scope","dataFactory",function($scope,dataFactory){
        $scope.title = "Hello World";
        dataFactory.getEntries("fakeSuffix");  
    }]);
    
    app.factory('dataFactory', ['$http', '$window', '$log', function ($http, $window, $log) {
        //var urlBase = $window.location.origin + '/api', 
        var urlBase = '/api',   //Change here.
        dataFactory = {};
        /**
        * get all Entries.
        **/
        dataFactory.getEntries = function (suffix) {
            $log.debug("************ Get All Entries ************");
            $log.debug("url:", urlBase + suffix);
            return $http.get(urlBase + suffix, { headers: { cache: false } });
        };
    
        /**
        * get single Entry.
        **/
        dataFactory.getEntry = function (id) {
            $log.debug("************ Get Single Entry ************");
            return $http.get(urlBase + '/' + id);
        };
    
        /**
        * insert Entry
        **/
        dataFactory.postEntry = function (method, entry) {
            var url = urlBase + '/' + method;
            return $http.post(url, entry);
        };
    
        /**
        * update Entry
        **/
        dataFactory.updateEntry = function (entry) {
            $log.debug("************ Update Single Entry ************");
            return $http.put(urlBase + '/' + entry.id, entry);
        };
    
        /**
        * delete Entry
        **/
        dataFactory.deleteEntry = function (id) {
            $log.debug("************ Delete Single Entry ************");
            return $http.delete(urlBase + '/' + id);
        };
    
        return dataFactory;
    }]);
    
    //Jasmine Test Case
    describe('factory: dataFactory', function() {
    
        var dataFactory, $http, $window, $log, $httpBackend;
    
        beforeEach(module('app'));
    
        beforeEach(inject(function (_dataFactory_, _$http_, _$window_, _$log_, _$httpBackend_) {
            dataFactory = _dataFactory_;
            $http = _$http_;
            $window = _$window_;
            $log = _$log_;
            $httpBackend = _$httpBackend_;
    
            $httpBackend.when('GET', "/api/suffix").respond({
                status: 200,
                data: "data"
            });
    
            $httpBackend.when('GET', "/api/id").respond({
                status: 200,
                data: "data"
            });
    
            $httpBackend.when('POST', "/api/method").respond({
                status: 200,
                data: "data"
            });
    
            $httpBackend.when('PUT', "/api/id").respond({
                status: 200,
                data: "data"
            });
    
            $httpBackend.when('DELETE', "/api/id").respond({
                status: 200,
                data: "data"
            });
        }));
    
        afterEach(function() {
            $httpBackend.verifyNoOutstandingExpectation();
            $httpBackend.verifyNoOutstandingRequest();
        });
    
        describe('function: getEntries', function(){
            //A sample test case for getEntries
            it('should get all enteries', function(){
                var response = dataFactory.getEntries("/suffix");
                response.then(function(res){
                    expect(res.status).toEqual(200);
                });
                $httpBackend.flush();
            });
        });
    
        //Similarly write tests for the rest of functions.
    
    });
    

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      据我所知,要测试服务,请创建类似于控制器的 Jasmine 测试用例,无需控制器初始化。

      要根据服务响应测试控制器,请为相应的服务创建 spyOn 并模拟服务响应。

      【讨论】:

        【解决方案3】:

        试试这个,在回答这个问题时找到Injecting a mock into an AngularJS service

          module(function($provide) {
              $provide.value('$http', {
                  get: function(url, options) {
                      // your get implementation
                  },
                  post: function(url, data) {
                      // your post implementation
                  },
                  'delete': function(url) {
                      // your delete implementation
                  },
                  put: function(url, data) {
                      // your put implementation
                  }
              });
          });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-04-11
          • 1970-01-01
          • 1970-01-01
          • 2014-05-20
          • 1970-01-01
          • 2016-12-31
          • 1970-01-01
          相关资源
          最近更新 更多