AngularJS+Jasmine: $httpBackend not working as expected AngularJS+Jasmine: $httpBackend not working as expected angularjs angularjs

AngularJS+Jasmine: $httpBackend not working as expected


Let's talk about each error separately:

Error: No pending request to flush!

That's happening because no request was made through $httpBackend, so there's nothing to flush. That's because you are instantiating UserService before $httpBackend and so Angular doesn't know it should use it instead of the real $http. If you check out the console you'll see that a real request is being sent.

Error: Unsatisfied requests: GET https://api.github.com/users/wilk

Same reason as the above. Since $httpBackend isn't being used by the service, the expectation you've created is never fulfilled.

Here's your spec refactored after considering all of the above:

describe ('Service: UserService', function () {    var UserService,        GITHUB_API_URL,        GITHUB_USER,        $httpBackend;    beforeEach(function() {      module('plunker');      inject(function( _$httpBackend_, _UserService_, _GITHUB_API_URL_, _GITHUB_USER_) {        $httpBackend = _$httpBackend_;        UserService = _UserService_;        GITHUB_API_URL = _GITHUB_API_URL_;        GITHUB_USER = _GITHUB_USER_;      });    });    afterEach (function () {        $httpBackend.verifyNoOutstandingExpectation ();        $httpBackend.verifyNoOutstandingRequest ();    });    describe ('when populate method is called', function () {        it ('should returns user data', function () {            $httpBackend              .whenGET(GITHUB_API_URL + '/users/' + GITHUB_USER)              .respond ({                  login: GITHUB_USER,                  id: 618009              });             UserService.populate(GITHUB_USER);            $httpBackend.flush();            expect(UserService.data().login).toBe(GITHUB_USER);            expect(UserService.data().id).toBe(618009);        });    });});

Plunker

Note: I've changed the way things were being injected a little bit, but the way you are doing is just fine, as long as you create $httpBackend before everything else.