mercredi 29 juillet 2015

AngularJS Unit Test using HttpBackend.whenGet doesn't return expected result

According to the Angular docs for ngMock the $httpBackend when method should intercept $http service requests and serve the specified response. I assume that the mock $httpBackend methods would be synchronous to make testing easier. But result.test ends up being undefined.

describe('Http requests', function () {
    var scope, $httpBackend, constituents;

    beforeEach(module('main'));

    beforeEach(inject(function (_$httpBackend_, _constituents_) {
        constituents = _constituents_;
        $httpBackend = _$httpBackend_;
    }));

    it('Should get the constituents', function () {
        $httpBackend.whenGET(webServicesPath + "api/constituents/all-constituents").respond(200, { "test": true });
        var result = constituents.getAllConstituents();
        //$httpBackend.flush();
        expect(result.test).toEqual(true);
    });

});

I tried using $httpBackend.flush() but that has unintended consequences leading to this...

Error: Unexpected request: GET App/Main/login.html

which means the ui.routing service got invoked somehow.

for reference, this is the factory used

app.factory('constituents', ['$http', '$log', function ($http, $log) {
    function getAllConstituents() {
        return $http.get(webServicesPath + "api/constituents/all-constituents").then(
            function (response) {
                return response.data;
            },
            function (response) {
                $log.error("Load Constituents - " + response.status + " " + response.statusText);
                return;
            }
        );
    }
    return {
        getAllConstituents: getAllConstituents
    }
}]);

Aucun commentaire:

Enregistrer un commentaire