If your test are hard to test, this means you are doing something wrong.
In your specific case, you need follow Dependency Inversion principle (think Dependency Injection) and inject your requirements into your function. Basically, you need to pass in all the dependencies including $
, successCallback
and failCallback
. This would let you mock your ajax calls with Jasmine's spyOn()
method and then check for correct function calls.
function sendRequestData(url, urlParameters, $, successCallBack, failCallBack) {
$.ajax({
url : url,
method : 'POST',
headers : {
'Accept' : 'application/json'
},
contentType : 'application/json',
data : JSON.stringify(urlParameters),
dataType : "json",
success : function(data) {
successCallBack(data)
},
error : function(data, status, errorThrown) {
failCallBack(data, status, errorThrown)
}
});
}
Your tests might look like this. I have not checked it, but you get an idea of what I mean.
describe("sendRequestData() does correct ajax calls", function() {
var $ok, $error, successCallback, failCallback = null;
beforeEach(function() {
// You can create a spy object using this syntax
$ok = jasmine.createSpyObj('$', ['ajax']);
// Or define it yourself like so
$ok = {
ajax: function(value) {
successCallback();
}
};
$error = {
ajax: function(value) {
failCallback();
}
};
spyOn($, 'ajax');
spyOn(successCallback);
spyOn(failCallback);
});
it("calls successCallback on success", function() {
sendRequestData('url', {}, $ok, successCallback, failCallback);
expect($.ajax).toHaveBeenCalled();
expect(successCallback).toHaveBeenCalled();
expect(failCallbackCallback).not.toHaveBeenCalled();
});
it("calls failCallback on failure", function() {
sendRequestData('url', {}, $error, successCallback, failCallback);
expect($.ajax).toHaveBeenCalled();
expect(successCallback).not.toHaveBeenCalled();
expect(failCallbackCallback).toHaveBeenCalled();
});
});
Or simply use jasmine-ajax plugin to mock your ajax calls.