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

标签 javascript angularjs rest mocking jasmine

嘿,我是 AngularJS 测试的新手,我正在尝试弄清楚,

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

  2. 如何在我想要测试的其他 Controller 中调用此服务。

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

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>

最佳答案

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

Q.2 - 我如何在我想要测试的其他 Controller 中调用此服务。
Ans. - 在下面的代码中,如您所示正在为您的服务编写测试用例,该服务依赖于 $httpgetpostputdelete 方法,我在测试用例中注入(inject)了 $httpBackend 并在 beforeEach block 中模拟了所有这些方法。同样,当您为依赖于此服务的 Controller 编写测试用例时,您必须使用类似的方法。只需将服务注入(inject) Controller 的测试用例中,并模拟将从 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.

});

希望这有帮助。

关于javascript - 如何在 Jasmin 中使用剩余调用来测试 AngularJS 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37813377/

相关文章:

javascript - 如何在选择菜单中的参数发生变化的情况下调用 knockout 方法?

javascript - 何时使用 JavaScript 中的函数?

javascript - 有没有办法从 JavaScript 中的 map 包含 block 返回?

javascript - 在 AngularJS 中将类设置为变量

java - 在 REST 调用上使 Java 服务器保持 DCOM 对象处于 Activity 状态

javascript - 使用 jquery load 动态加载页面

mysql - Sequelize 属于ToMany 不起作用

angularjs - 当 $state.go 调用 $stateChangeStart 时,Angular 1.4.1 UI 路由器 10 $digest() 迭代

jquery - 当 POST 方法失败时,如何修复 Jquery 上的 cors origin 错误?

javascript - 如何从 JavaScript 调用 REST Web 服务 API?