Following the official guide at angularJS $httpBackend I'll do this test, but Karma give me this error:
Error: No pending request to flush !
at Function.$httpBackend.flush
Test
'use strict';
describe('profileCtrl', function () {
var scope, $httpBackend;
beforeEach(angular.mock.module('maap'));
beforeEach(angular.mock.inject(function($rootScope, $controller, _$httpBackend_){
$httpBackend = _$httpBackend_;
$httpBackend.when('GET', 'profile').respond([{id: 1, name: 'Bob'}]);
scope = $rootScope.$new();
$controller('profileCtrl', {$scope: scope});
}))
it('should fetch list of users', function(){
$httpBackend.flush();
expectGET(scope.current_user.length).toBe(1);
expect(scope.current_user[0].name).toBe('Bob');
});
});
for this simple controller:
'use strict';
angular.module('maap').controller('profileCtrl', function($scope, UserService) {
$scope.current_user = UserService.details(0);
});
The
_$httpBackend_
has nothing to flush because you don't make any http request in your test.You need to invoke some code that make an http request.
Then, once something somewhere made an http request in your test, you can call the
flush
method so that a response is provided for the request that has been made.Something like:
I've got the same exception because I used ngMockE2E module instead of ngMock module. Even calling $rootScope.$digest() didn't help.
I had the same issue, because I neglected to define a response for each expected request. With no response, there becomes nothing to flush. Also the http promise would never resolve or fail.
Same issue happened to me and the problem was not that I was not making a request but because the request I was making was different to the expected one:
For example I have defined this expectation:
And I was requesting this other URL:
Very confusing error message, no really easily related with the underneath problem.