0

Here's a simplified version of my code:

Plunker: https://plnkr.co/edit/ZlX8oV2bMtzXrxtwGX8q?p=preview

angular.module('test', []).factory('test', function ($http) {
    var service = {};

    service.load = function () {
        return $http.get('api/test');
    };

    return service;
})

describe('test', function () {
    var test;
    var $httpBackend;
    var $q;
    var $rootScope;

    beforeEach(angular.mock.module('test'));

    beforeEach(inject(function (_test_, _$httpBackend_, _$rootScope_) {
        test = _test_;
        $httpBackend = _$httpBackend_;
        $rootScope = _$rootScope_;
    }));

    afterEach(function() {
        $httpBackend.verifyNoOutstandingExpectation();
        $httpBackend.verifyNoOutstandingRequest();
    });

    it('should be defined', function (done) {
        var expected = 123;
        $httpBackend.whenGET('api/test').respond(expected);
        var promise = test.load();

        promise.then(function (result) {
            expect(result.data).toBe(expected);
            done();
        });

        $httpBackend.flush();
        $rootScope.$apply();
    });
}); 

I'm already calling $rootScope.$apply() like this answer suggests.

The test runner is timing out. That means done() is never getting called. That means the function passed into then is never getting called. How do I get that function called? I would expect triggering a digest cycle to do it.

Jesus is Lord
  • 14,971
  • 11
  • 66
  • 97

1 Answers1

0

The first argument to respond should be the status code.

$httpBackend.verifyNoOutstandingExpectation(); was giving an error, so I took that out.

angular.module('test', []).factory('test', function ($http) {
    var service = {};

    service.load = function () {
        return $http.get('api/test');
    };

    return service;
})

describe('test', function () {
    var test;
    var $httpBackend;
    var $q;
    var $rootScope;

    beforeEach(angular.mock.module('test'));

    beforeEach(inject(function (_test_, _$httpBackend_, _$rootScope_) {
        test = _test_;
        $httpBackend = _$httpBackend_;
        $rootScope = _$rootScope_;
    }));

    afterEach(function() {
        $httpBackend.verifyNoOutstandingRequest();
    });

    it('should be defined', function (done) {
        var expected = 123;
        $httpBackend.whenGET('api/test').respond(200, expected);
        var promise = test.load();

        promise.then(function (result) {
            expect(result.data).toBe(expected);
            done();
            console.log('here');
        });

        $httpBackend.flush();
    });
}); 
Jesus is Lord
  • 14,971
  • 11
  • 66
  • 97