dimanche 11 octobre 2015

Cannot get $httpBackend to work correctly with Jasmine test of Angular Async function

I have the following code in a test function

var ReadingLog;
(function (ReadingLog) {
    var Tests;
    (function (Tests) {
        var Security;
        (function (Security) {
            describe('Data', function () {
                describe('Goal Data Service', function () {
                    var $http;
                    var $httpBackend;
                    var $q;
                    beforeEach(inject(function (_$http_, _$httpBackend_, _$q_) {
                        $http = _$http_;
                        $httpBackend = _$httpBackend_;
                        $q = _$q_;
                    }));
                    describe('Async', function () {
                        var readerId = '-1';
                        var goal = new ReadingLog.Models.Goal();
                        var result;
                        beforeEach(function (done) {
                            $httpBackend.when('PUT', /.*/).respond({
                                'Success': true,
                                'ErrorMessage': '',
                                'Result': goal
                            });
                            var dataService = new ReadingLog.Data.GoalDataService($http, $q);
                            dataService.create(goal, readerId)
                                .then(function (results) {
                                result = results;
                                done();
                            });
                        });
                        it('Create', function () {
                            expect(result).toBe(goal);
                        });
                    });
                });
            });
        })(Security = Tests.Security || (Tests.Security = {}));
    })(Tests = ReadingLog.Tests || (ReadingLog.Tests = {}));
})(ReadingLog || (ReadingLog = {}));

Which you can see is call to the create function on the GoalDataService class. I have angular and Angular Mock loaded into this test and you can see that it is using the $httpBackend to say whenever a PUT command is issued it should return a goal object and then in the test itself I'm expect that the result of the call should be that Goal object.

When this runs all that I'm getting is a timeout error from the Jasmine test engine. Saying that the done method is never called. Which is what I'm seeing when I put various breakpoints in. The then method to the dataService call is never getting hit. I'm assuming that this is because the httpBackend setup is not working correctly for some reason.

The create method is simple a call to the $http.put function, passing in the item the goal that is passed to the create function, using the reader parameter to build the correct URL.

Aucun commentaire:

Enregistrer un commentaire