简体   繁体   English

如何在Jasmin中使用剩余调用测试AngularJS服务

[英]how to test an AngularJS service with rest calls in Jasmin

Hey I am new to AngularJS testing, I am trying to figure out, 嘿,我是AngularJS测试的新手,我试图弄清楚,

  1. How should I test an AngularJS service which is responsible for my rest calls. 我应该如何测试负责我的休息电话的AngularJS服务。

  2. How do I called this service in other controllers which I want to test. 如何在我要测试的其他控制器中调用此服务。

I need to test the datafactory service which use rest requests The code which need to be tested is like this: 我需要测试使用rest请求的datafactory服务。需要测试的代码如下:

 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> 

Try this, found in answer to this question Injecting a mock into an AngularJS service 尝试一下,在此问题的答案中找到将模拟注入AngularJS服务

  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
          }
      });
  });

As for as I know, To test service, create the Jasmine test case similar to controller with out controller initialisation. 据我所知,要测试服务,请在不进行控制器初始化的情况下创建类似于控制器的Jasmine测试用例。

To Test the controllers based on service response create spyOn for the respective service and mock the service response. 要基于服务响应测试控制器,请为相应的服务创建spyOn并模拟服务响应。

Q.1 - How should I test an AngularJS service which is responsible for my rest calls. Q.1-我应该如何测试负责我的休息电话的AngularJS服务。
Ans. Ans。 - I've written a test case for one of your services' methods below. -我为下面的一种服务方法编写了一个测试案例。 You can write similar test cases for other methods. 您可以为其他方法编写类似的测试用例。

Q.2 - How do I called this service in other controllers which I want to test. 问题2-如何在要测试的其他控制器中调用此服务。
Ans. Ans。 - In the code below, as you are writing test cases for your service which is relying on $http 's get , post , put and delete methods, I've injected $httpBackend in the test cases and mocked all these methods in beforeEach block. -在下面的代码中,当您根据$httpgetpostputdelete方法$httpBackend的测试用例时,我在$httpBackend中注入了$httpBackend ,并在beforeEach块中beforeEach所有这些方法。 Similarly, when you'll be writing test cases for your controller which would be depending on this service, you'll have to use a similar approach. 同样,当您要为控制器编写测试用例(取决于此服务)时,必须使用类似的方法。 Just inject the service in your controller's test case and mock all the methods of your service that would be called from your controller. 只需将服务插入控制器的测试用例中,并模拟将要从控制器调用的服务的所有方法。

//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.

});

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM