tangokhi
tangokhi

Reputation: 1015

Verifying a call on $httpBackend in angularjs test

I am trying to write a test for angularjs which is mocking $httpBackend. Following is the test.

describe('test', function() {

    beforeEach(function (){
        module('abcApp');
    });

    var $httpBackend, filterService;
    beforeEach(inject(function($injector) {
        $httpBackend = $injector.get('$httpBackend');
        filterService = $injector.get('filterService');
    }));

    it('getCompany calls get on http with correct parameter', function () {
        $httpBackend.when('GET', 'api/Abc').respond([]);
        filterService.getAbc();
        $httpBackend.flush();
        expect($httpBackend.get).toHaveBeenCalled();
    });
});

when I run the test I get the following error:- Error: Expected a spy, but got undefined.

Any ideas how I would I assert that $httpBackend.get have been called with required parameter using expect.

Upvotes: 4

Views: 2377

Answers (1)

JB Nizet
JB Nizet

Reputation: 691715

expect($httpBackend.get).toHaveBeenCalled();

is invalid. First because $httpBackend doesn't have any (documented) get() method. Second, because $httpBackend.get is not spied by Jasmine, so you can't add Jasmine if this method has been called.

You should just test that, given the empty array returned by the http backend, the service returns the right thing, or has the desired side effect. You could also use

$httpBackend.expectGET('api/Abc').respond([]);

and

$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();

so that $httpBackend verifies for you that the expected request has been sent.

Upvotes: 6

Related Questions