Exploring the proper method for mocking an http post with a custom transform in Angular using the Sinon mocking framework.
In my CoffeeScript Sinon unit test setup, I define mocks like this:
beforeEach module(($provide) ->
mockHttp = {}
$provide.value('$http', mockHttp))
I then verify that it is being called with
expect(mockHttp.post).to.have.been.calledWith('/api/v1/something/' + id)
As per Sinon's documentation, mocking a method call for a standard get or post transform appears as follows:
mockHttp.post.returns(q.when({}))
This translates to "upon calling the post, return a promise containing an empty object".
While this mock setup works for JavaScript code similar to this example:
service.create = function(arg) {
return $http.post('/api/v1/something/' + arg {token: token }).then(
function(response) {
return response.data;
}
);
};
The challenge arises when there is no method called directly on the line "$http.post", but rather in a nested function like:
service.customPostback = function(arg1) {
return service.doSomething(arg1).then(
function(response) {
return $http.post(
'http://mypostback.url',
{
"name":"value"
}
).then(function(response) {
return response.data;
});
}
);
};
To deal with cases like this in Angular, refer to Overriding the Default Transformations Per Request
The current mock setup may not cover the callback inside doSomething(arg1). Upon running my test, I find that mockHttp.post is not being triggered.
What would be the appropriate mock setup for this type of JavaScript function?