Rebekah Waterbury
Rebekah Waterbury

Reputation: 23796

Testing a basic Angular Service

Ok so this is my setup:

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;
    }); 
  }
});

Here's my jasmine test file:

(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();
      });  

    })  

  })  

})();

So when I run this elbService.remove_instance(1,1) returns undefined. Any ideas why?

Upvotes: 0

Views: 42

Answers (1)

baweaver
baweaver

Reputation: 306

As mentioned there by @tymeJV, you need to return the $http object as well or set a scope variable equal to the response. As is, the problem is you're returning up only one level, not two:

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

See this fiddle: http://jsfiddle.net/v80dLmwz/

Upvotes: 1

Related Questions