Reputation: 841
I have below ajax call code in my .js file and I want to write jasmine unit tests to bring coverage.
var promise = $.ajax({
url: URL,
type: 'GET'
});
promise.done(function(data, status) {
console.log("success");
});
promise.fail(function(status, error) {
console.log("error");
});
I am able to write unit test case for $.ajax calls by stubbing/mocking data, but not able to write test case for .done and .fail methods. Is there anyway to write specs for .done and .fail methods.
Upvotes: 0
Views: 2423
Reputation: 2685
Here is how I slightly modified your question to suit mock behavior. See it in action here
var handler = {
success: function(data) {
console.log("success");
},
fail: function(data) {
console.log("error");
}
};
var testObj = {
ajaxFunction: function() {
var promise =
$.ajax({
url: 'abc',
type: 'GET'
});
promise.done(function(data, status) {
handler.success(data);
});
promise.fail(function(status, error) {
handler.fail(error);
});
}
};
describe('test ajax', function() {
it('test success', function() {
spyOn(handler, 'success').and.callFake(function(e) {
console.log("This is a spy call for success handler");
});
spyOn($, 'ajax').and.callFake(function(e) {
return $.Deferred().resolve({
'hurray': 'success'
}).promise();
});
testObj.ajaxFunction();
expect(handler.success).toHaveBeenCalled();
});
it('test failure', function() {
spyOn(handler, 'fail').and.callFake(function(e) {
console.log("This is a spy call for fail handler");
});
spyOn($, 'ajax').and.callFake(function(e) {
return $.Deferred().reject({
'alas': 'failure'
}).promise();
});
testObj.ajaxFunction();
expect(handler.fail).toHaveBeenCalled();
});
});
Upvotes: 2
Reputation: 6912
To write test cases for .done
and .fail
methods you would need to create the Spy
on $.ajax
JQuery function, and call your own fake function where you would create Deferred
object and resolve/reject it depends on your test. For example you code may looks like ...
// successful case
spyOn($, "ajax").and.callFake(function () {
return $.Deferred().resolve(expected_data, expected_status).promise();
});
// failure case
spyOn($, "ajax").and.callFake(function () {
return $.Deferred().reject(expected_status, expected_error).promise();
});
Upvotes: 0