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