AngularJS + Jasmine模拟单元测试$ http工厂的POST方法

时间:2015-09-09 14:42:34

标签: angularjs unit-testing karma-jasmine

如果使用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         没有更多的要求 "

0 个答案:

没有答案