I have a function on my service that looks like something this:
addStatement: function(user, action, object) {
var statement = {
user: user,
action: action,
object: object
};
$http({
method: 'POST',
url: '/foo/bar',
data: statement,
headers: {Authorization: 'Basic YWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
}).success(function(data) {
alert("success: " + data);
});
}
I want to write a unit test for this method, but I’m not sure how to make it work. Basically, I want to test that the data sent up was correctly constructed from the function parameters and that the correct Authorization header was sent up.
I’ve been reading over how to use $httpBackend, but the example there is testing a controller, and just stuff that changes on the $scope when the requests are made and returned. Is there a way to achieve the tests I want? Or am I going about something wrong?
Testing services doesn’t differ much from testing controllers so the principles are the same. Basically you need to:
If you are after testing that a service methods results in $http POST call you could write your test like this (non-essential parts omitted):
Here is the working jsFiddle illustrating this test in action: http://jsfiddle.net/pkozlowski_opensource/MkrjZ/2/
One last remark: it is better not to use .alert() in unit tests since those alerts will pause execution of tests.