2014-04-19 59 views
0

我有一个简单的服务,我想测试。我使用$ httpBackend来模拟请求。在ajax调用之后,我遇到了模拟数据的问题。我知道它是异步的。我需要一种简单的方法将模拟的数据返回。

angular.module('adminApp').service("categoryService", function ($http) { 

    this.getAllCategories = function() { 
     console.log("GOING TO CALL GET"); 
     $http.get("./category/categories").success(function(data, status, headers){ 
      console.log("IN SUCCESS", data); // the right data is displayed but not returned to the test 
      // i need to do something here to return the data to my test 
      return data; 
     }).error(function(data, status, headers, config){ 
      console.log("ERROR: ", data,status,headers,config); 
     }); 

    }; 
}); 

测试

describe("Category Service Tests", function() { 

    var myCategoryService, $httpBackend; 

    beforeEach(module("adminApp")); 

    beforeEach(inject(function (categoryService,_$httpBackend_) { 
     $httpBackend = _$httpBackend_; 
     $httpBackend.when("GET", "./category/categories").respond(["hello","world"]); 
     myCategoryService = categoryService; 
    })); 

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

    it('should not be undefined', function() { 
     expect($httpBackend).toBeDefined(); 
    }); 

    it("Should not be null", function() { 
     expect(myCategoryService).toBeDefined(); 
    }); 

    it("Should return all available categories", function() { 
     $httpBackend.expect("GET",'./category/categories'); 
     var categoriesList = myCategoryService.getAllCategories(); 
     $httpBackend.flush(); 
     console.log(categoriesList); 

     expect(categoriesList.length).toBe(2); 
}); 


}); 

回答

0

你的代码已经有问题,这将在一定测试失败。您的代码的问题是您在异步函数后立即返回数据,那时dataToSend尚未更新

尝试更新你这样的代码:

app.service("categoryService", function ($http) { 

    this.getAllCategories = function (callback) { 

     $http.get("./category/categories").success(function(data, status, headers){ 
      callback(data); 
     }).error(function(data, status, headers, config){ 
      console.log("ERROR: ", data,status,headers,config); 
     }); 
    }; 
}); 

你的检查:

it("Should return all available categories", function() { 
     $httpBackend.expect("GET",'./category/categories'); 
     var categoriesList; 
     myCategoryService.getAllCategories(function(data){ 
      categoriesList = data; 
     }); 
     $httpBackend.flush(); 
     console.log(categoriesList); 

     expect(categoriesList.length).toBe(2); 
    }); 

DEMO