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_;
$httpBackend.expectGET("App/Main/login.html").respond(200);
}));
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.$$state.value.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. so I handled that by adding a $httpBackend.expectGET... in the beforeEach.
Why do I have to even use the flush method? Seems overly complicated. Why does it trigger ui.routing when that has nothing to do with my unit test?
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
}
}]);
webServicesPathvariable coming from? It seems to beundefinedin both your spec and your factory.