I can fake ajax with both of these tools. Sinon allow to create stub/spy/mock that come handy for testing and mockjax doesn't. When it come to faking ajax call, does mockjax provide more features then Sinon? Cause if it doesn't, there is no point is using both of them.
var response = [];
var statusCode = 200;
var responseTime = 0;
Example how to fake ajax call with mockjax :
$.mockjax({
url: server_api_url + "/Something/GetData",
status: statusCode,
responseTime: responseTime,
contentType: "application/json",
responseText: response
});
Example how to fake ajax call with Sinon.js :
var def = $.Deferred();
var stubGetData = sinon.stub(serverApiForSomething, "GetData");
def.resolve(response);
stubGetData.returns(def);
Where serverApiForSomething is a global class that encapsulate ajax call.
ServerApiForSomething = function()
{
var self = this;
self.GetData = function(param)
{
var ajaxOption =
{
url:server_Api_Url + "/Something/GetData",
type: "GET",
data: { param.toJSON() },
contentType: "application/json",
dataType: "json"
}
return $.ajax(ajaxOption);
}
}
serverApiForSomething = new ServerApiForSomething();
I'm the maintainer of the Mockjax plugin. I would agree with @AXMIM's comments that Mockjax has some cool built-in features specifically for mocking ajax calls, but it also is only intended to be used with jQuery, where as Sinon can be used with any framework (but doesn't have quite as many built-in cool things).
That said, looking at your code, you are not really mocking an Ajax call with that Sinon code, you're mocking out the
GetData
method. That's cool too, but not really the point of Mockjax, which is take the Ajax call out of the picture but leave everything else in place. The proper comparison is using Sinon'sFakeServer
feaure.Really, you can use both, if you like the syntax of Mockjax better, then use that for mocking Ajax, and use Sinon to spy on the success and error handlers.