0

I'm running into trouble trying to mock my $http calls in Angular. When calling $httpBackend.flush() I'm getting the error: Error: No pending request to flush !

I've read up on many other posts of similar issues on here, but I still can't seem to get it to work by adding $rootScope.$digest() or adding $httpBackend.expect

I'm testing a service function:

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

Using this .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();

        });

    });
});
});
jbenowitz
  • 1,795
  • 6
  • 26
  • 39
  • Where's the `itemAPI` variable being instantied? – Michael Benford Aug 27 '13 at 21:14
  • Removed that from the code on here because I thought it was an irrelevant test. Added now. It's just instantiated on an it cause above what I test. – jbenowitz Aug 27 '13 at 21:19
  • I see. You should create it inside a `beforeEach` call in order to ensure it'll be defined regardless of the order the tests run. Back to your problem, I wonder if you can create a Plunker script showing the "No pending request to flush" error? It'd be easier to debug it there. – Michael Benford Aug 27 '13 at 21:55
  • Oh man, you're completely right. The `beforeEach` did it. This is what happens when I jump from unit testing to regular javascript. Thanks a bunch. That was a stupid mistake. – jbenowitz Aug 27 '13 at 22:18
  • That's odd. If the `itemAPI` variable wasn't defined when the `get all items` test ran, how come you didn't get an error on `itemAPI.getAll(...)` line? – Michael Benford Aug 27 '13 at 22:46
  • I have no idea. But moving the injection and variable to the before each worked. Strange, isn't it? – jbenowitz Aug 29 '13 at 15:01

0 Answers0