0

我在尝试在 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();

        });

    });
});
});
4

0 回答 0