2014-02-13 94 views
1

我在用Jasmine測試AngularJs中的HTTP POST時遇到了一些麻煩。

我有一個控制器,它看起來像這樣: -

appControllers.controller("TaskAddController", function ($scope, $http) { 
    $scope.task = {}; 
    $scope.messages = {}; 

    $scope.actions = { 
     save : function() { 
      $http.post("/ajax/tasks/save", $scope.task) 
      .then(function() { 
       $scope.messages.success = true; 
       $scope.task = {}; 
      }); 
     } 
    }; 
}); 

我像這樣測試它: -

describe("TaskAddController", function() { 
    var createController, scope, $httpBackend; 

    beforeEach(function() { 
     module('appControllers'); 

     scope = {}; 

     inject(function ($injector) { 
      $httpBackend = $injector.get("$httpBackend"); 
     }); 

     inject(function ($controller) { 
      createController = function() { 
       return $controller("TaskAddController", { $scope: scope }); 
      }; 
     }); 
    }); 

    afterEach(function() { 
     $httpBackend.verifyNoOutstandingExpectation(); 
     $httpBackend.verifyNoOutstandingRequest(); 
    }); 

    it("when actions.save is called then should call service", function() { 
     var task = { 
      title: "Title", 
      description: "Description" 
     }; 

     $httpBackend.expectPOST("/ajax/tasks/save", task); 
     createController(); 
     scope.task = task; 
     scope.actions.save(); 
     $httpBackend.flush(); 
    }); 
}); 

這使我得到以下錯誤Error: No pending request to flush !

什麼我做錯了嗎?

謝謝。

回答

3

您正在使用什麼版本的AngularJS?

當我運行的代碼我得到:Error: No response defined !

當我添加測試通過的響應:

$httpBackend.expectPOST("/ajax/tasks/save", task).respond({}); 
+0

完美的感謝。我不能相信我錯過了這一點。爲了讓我在深夜嘗試做事而爲我服務! – baynezy