测试基本的Angular服务

时间:2014-09-15 20:58:43

标签: javascript angularjs jasmine httpbackend

好的,这是我的设置:

var app = angular.module("KamajiDash", ['ngResource','ui.bootstrap'.. 'elasticsearch']);

app.service("elbService",function($http) {
  this.remove_instance =  function(elb_id, instance_id) {
      $http.delete("/api/v1/amazon_elbs/"+elb_id+"/remove_instance/"+instance_id).success(function(data){
        return data;
      }).error(function(error){
        return error;
    }); 
  }
});

这是我的茉莉花测试文件:

(function(){

  var elbService, httpBackend;

  describe ('elbService', function(){

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

      inject(function(_elbService_,$httpBackend){
        httpBackend = $httpBackend;
        elbService = _elbService_;
      }); 
    }); 

    describe("#remove_instances", function(){

      beforeEach(function(){
        httpBackend.when("DELETE","/api/v1/amazon_elbs/1/remove_instance/1").respond("success")
      })  

      it("will provide a method called remove instances, that take two args, that calls $http.delete with the correct url", function(){
        elbService.remove_instance(1,1).then(function(response){
          expect(response).toEqual("success");
        });  
        httpBackend.flush();
      });  

    })  

  })  

})();

所以当我运行这个elbService.remove_instance(1,1)时返回undefined。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

如@tymeJV所述,您还需要返回$ http对象或将范围变量设置为等于响应。问题是,问题是你只返回一个级别,而不是两个级别:

a = function () {
  function() { return 1; }() // 1 is visible here
}() // ... but not here

看到这个小提琴:http://jsfiddle.net/v80dLmwz/