使用$ httpBackend测试一个简单的服务

时间:2014-04-19 10:10:16

标签: javascript angularjs testing jasmine

我有一个我想测试的简单服务。我使用$ 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);
});


});

1 个答案:

答案 0 :(得分: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