I'm writing a test to simply check that an endpoint is being called by a service. I'm using $httpBackend
to mock this response, however the test is still hitting the real backend endpoint, and not using the $httpBackend
mock.
Service
function getOptions() {
return $http.get('/apiv1/something').then(function (data) {
return [{
name: "eGo C"
image: "http://www.google.co.uk/logo.png"
}];
};
}
Test
describe('product service', function () {
var $httpBackend, service, $rootScope;
var failTest = function (error) {
expect(error).toBeUndefined();
};
beforeEach(module('appName'));
beforeEach(inject(function (_$httpBackend_, productService, _$rootScope_) {
$httpBackend = _$httpBackend_;
$rootScope = _$rootScope_;
service = productService;
}));
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
describe('getOptions', function () {
it('should make a call to the backend', function () {
var handler,
myThings,
errorStatus,
mockResponce;
mockResponce = [
{
name: 'evod kit',
img: 'img.jpg'
}
];
myThings = [];
errorStatus = '';
handler = {
success: function(data) {
console.log("success " + data);
myThings = data;
},
error: function(data) {
console.log("error " + data);
errorStatus = data;
}
};
spyOn(handler, 'success').and.callThrough();
spyOn(handler, 'error').and.callThrough()
$httpBackend.when('GET', '/apiv1/something').respond(mockResponce);
service.getOptions().then(handler.success, handler.error);
$httpBackend.flush();
console.log("MY THINGS ", myThings);
// PROBLEM!!! == FROM THE SERVICE -> [{name: "eGo C"
// image: "http://www.google.co.uk/logo.png"
// }]
});
});
Essentially.. I'm an idiot. In the service I was returning a hardcoded array as the backend is yet to be built. $httpBackend was doing its job and returning the new data, but of course, it was not getting returned by the service. Sigh. I need a beer.