【问题标题】:AngularJS + Jasmine mock unit test $http factory of POST methodAngularJS + Jasmine 模拟单元测试 $http 工厂的 POST 方法
【发布时间】:2015-09-09 14:42:34
【问题描述】:

如果使用 post 方法,我如何对 $http 工厂进行单元测试,例如:

// controller

  $scope.logOut = function (){
    logOutFactory.logOut().then(function(resp){
    });
  };


// service 

app.factory('logOutFactory', ['$http', '$q', 'CONST', function ($http, $q, CONST){
    var logoutApiUrl = CONST.URL+'logout';
    return {
        logOut: function() {
            var deferred = $q.defer();
                $http({
                    method: "post",
                    url: logoutApiUrl
                })
                .success(function (data) {
                    deferred.resolve(data);
                })
                .error(function (data) {
                deferred.reject('error in $http request');
                console.log(data, status, headers, config);
                });
            return deferred.promise;
        }
    }
}]);

// unit test

describe("myApp", function () {
 
beforeEach(module('app'));
describe("Ctrl", function () {
    var scope, httpBackend, fakedMainResponse;


    beforeEach(inject(function ($rootScope, $controller, $httpBackend, $http) {
        scope = $rootScope.$new();
        httpBackend = $httpBackend;
        httpBackend.expectPOST('https://url/logout').respond(200);
        $controller('Ctrl', {
            $scope: scope,
            $http: $http
        });
    }));
 
    it("success response - empty array from server", function () {
       //httpBackend.flush();
    });
});
});

我如何在 Jasmine 测试中模拟 $http 响应? 我正在尝试,但我看到一个错误“错误:意外请求:POST /url/logout 预计不再有请求 "

【问题讨论】:

    标签: angularjs unit-testing karma-jasmine


    【解决方案1】:

    您想为 $http 工厂编写一个单元测试,但在您的测试中,里面有一个 $controller。也许您应该将此测试分为 2 个单元测试,一个用于控制器,一个用于工厂。

    当你测试 logOutFactory 时,你应该创建一个 $httpBackend 来模拟后端,以及 logOutFactory

    var logOutFactory, httpBackend;
    

    beforeEach中,只需要初始化这2个变量即可:

    beforeeach(inject(function($httpBackend, logOutFactory) {
        httpBackend = $httpBackend;
        logOutFactory = logOutFactory;
    }));
    

    并在测试方法中模拟httpBackend:

    it("success response - empty array from server", function () {
        httpBackend.expectPOST('https://url/logout').respond(200);
        var success;
        // call logOut
        logOutFactory.logOut().then(function () {
            success = true;
        });        
        httpBackend.flush();
        // verification
        expect(succeeded).to.be.true;
    });
    

    【讨论】:

      猜你喜欢
      • 2017-10-07
      • 2016-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多