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