在Angular 1.1.5中测试$ http调用

时间:2013-08-27 20:12:50

标签: unit-testing angularjs jasmine karma-runner angular-http

我在尝试模拟Angular中的$ http调用时遇到了麻烦。致电$httpBackend.flush()时,我收到错误:Error: No pending request to flush !

我已在此处阅读了许多类似问题的其他帖子,但我似乎无法通过添加$rootScope.$digest()或添加$httpBackend.expect

来使其工作

我正在测试服务功能:

getAll: function (success, error) {
            $http.get(apiRootService.getAPIRootHTTP() + "/items")
                .success(success).error(error);
},

使用此.spec:

describe ('itemAPI Module', function (){
var $httpBackend, $rootScope, itemAPI, apiRootService;
var projectID = 123;

beforeEach(module('itemAPI'));
beforeEach(module('mApp'));

/**
 * Set up variables pre-insertion
 */
beforeEach( inject( function(_$rootScope_, _$httpBackend_, _apiRootService_){
    $httpBackend = _$httpBackend_;
    $rootScope = _$rootScope_;
    apiRootService = _apiRootService_;
}));


describe('itemAPI factory', function (){

    it('can get an instance of the metaAPI factory', inject(function(_itemAPI_){
        itemAPI = _itemAPI_;
        expect(metaAPI).toBeDefined();
    }));

    describe("get all items", function (){

        it("will return an error", function (){
            var url = apiRootService.getAPIRootHTTP() + "/items";
            $httpBackend.whenGET(url)
                .respond(400);

            var error;
            itemAPI.getAll(
                function(data, status){
                   //this is success
                },
                function(data, status){
                    error = true;
            });

            $httpBackend.expectGET(url);
            $rootScope.$digest();
            $httpBackend.flush();
            expect(error).toBeTruthy();

        });

    });
});
});

0 个答案:

没有答案