Angularjs-mock testing $http by mocking using httpBackend and flush() not working.


I was writing a unit test for my angularjs app and I ran into the following problem.

I was setting up the test correctly to inject in the $httpBackend to mock out the http calls, but the when I called called the service and then called $httpBackend.flush() it would return an error:

httpBackend no pending request to flush

Which is not what I was expecting.

Other background

When I commented out the $httpBackend.whenGET
The following 2 methods in the afterEach function would not throw an error either.


This would pass the test even though the expectations were never triggered.

Here is an example of the code I was testing with.

Code example

describe('MyService', function () {
	var service, $httpBackend, response;

	beforeEach(inject(function( _$httpBackend_, MyService) {
		$httpBackend = _$httpBackend_;
		response = null;
		service = MyService;
		return service;


	it('when we call fetchNames starting with Ab', inject(function (){
	    response = service.fetchNames('foo');

	    $httpBackend.flush();  //this would throw an error with wrong version of mocks injected into your test

	    response.success(function(body) {
                console.log('this is a success');
            }).error(function(body) {
        	throw new Error('this should not fail');



My angular-mocks.js version was not upgraded when the rest of the app version was in production.  I was running:

angular version 1.2.6

angularjs-mocks version 1.0.9


Upgrade the angularjs-mocks to version 1.2.6 and it throws the correct exceptions and fulfils the correct expectations..


One thought on “Angularjs-mock testing $http by mocking using httpBackend and flush() not working.

  1. Erm

    Wow, thank you so much for posting this. I would’ve been debugging this for quite some time considering that there’s no documentation anywhere, and it wasn’t immediately obvious to me that I had two different versions.

    I really love AngularJS, it has great documentation and it simplifies a lot, but I really wish that some of the error messages were more descriptive, since it’s not feasible to be debugging angular.min.js from a cryptic stack trace…


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s