In my AngularJS application, I am having trouble figuring out how to unit test the following code:
This is the service being used by my test controller:
angular
.module('web.template')
.factory('testService', testService);
testService.$inject = ['$http'];
function testService($http) {
return {
getTestDatas: function (callback) {
var data = {
'testParams': "test"
};
$http.post('http://localhost/test/post', data)
.success(function (response) {
callback(response);
});
},
};
};
As described in the docs you can use
$httpBackend
to make a mock for$http
.You can test both ways of implementing the service (callback or promise). But I also think that promises are better to test and should be preferred.
Just include
ngMock
in your dependencies and then you can create a fake response for your url.Please have a look at the demo below (not working on SO, need to check what's the problem) or the working demo at jsFiddle