We have a what we call a CORShttpService, which is basically a wrapper aroung the $http service, but encapsulates some CORS functionality that we need. I’m now writing some tests for a service that has the CORShttpService injected into it. This service has code like this:
CORShttpService({method: requestMethod, url: getUrl(path), data: data}).
success(function(data, status, headers) {
//do success stuff
}).
error(function(data, status, headers) {
//do error stuff
});
I want to mock the call to CORShttpService, but I’m not sure how to go about doing it. I’m using Jasmine, and its spyOn function requires an object to mock the function on the object. My CORShttpService isn’t attached to any object, so I don’t know how to go about mocking it. Yes, I could use $httpBackend to mock the requests that eventually get set in the CORShttpService, but I don’t want it going into that service in the first place. I want to isolate the unit test and simply mock the external calls. Is there any way I can mock this service that is just a function?
As I thought about this more, the
$httpBackendservice does provide a lot of functionality for testing requests. As myCORShttpServiceis a basically a wrapper around$http, I decided I could probably get the most bang for my buck, if I made the mock implementation ofCORShttpServicesimple the$httpimplementation. Using this documentation to help me, I have the following in my spec:So, any of my services wanting the
CORShttpServiceinjected, will now basically just have$httpinjected, and thus allow me to use all the$httpBackendfunctionality without the concern of the extra functionality found in theCORShttpServiceitself.This works for my specific case, but as far as a general solution for mocking services that are just a function, the same kind of thing could probably be done with
jasmine.createSpyas mentioned in zbynour’s answer. Something like: