I am trying to spy the ajax error request and getting the below error. Can you help on this.
TypeError: e.error is not a function
function postSettings() {
$.ajax(
{
type: "POST",
url: EndPoints.Setup,
data: frm_data,
success: function (successData) {
///// code is getting covered
},
error: function (errorData) {
///// code is not getting covered
}
});
}
describe("Call Success path", function () {
var ajaxSpy;
beforeEach(function () {
var MockEndPoints = global.EndPoints = {};
MockEndPoints.SnmpSetup = "/mock/test/setup";
ajaxSpy = spyOn($, "ajax").and.callFake(function (e) {
e.success(globalFakeData);
});
});
it("Should populate settings", function () {
Setup.postSettings();
expect($.ajax).toHaveBeenCalledTimes(2);
});
});
describe("Call Error path", function () {
var ajaxSpy;
beforeEach(function () {
var MockEndPoints = global.EndPoints = {};
MockEndPoints.SnmpSetup = "/mock/test/setup";
ajaxSpy = spyOn($, "ajax").and.callFake(function (e) {
**e.error; // No error but the path is not covered**
**e.error(globalFakeData); // throws the above error**
});
});
it("Should populate settings", function () {
Setup.postSettings();
expect($.ajax).toHaveBeenCalledTimes(1);
});
});
Thanks.
I'd strongly suggest not trying to spy on / stub $.ajax methods directly, and instead use the jasmine-ajax library.
In a beforeEach do: jasmine.Ajax.install().
Run your test code, and you can check the ajax request has been made (and intercepted) with var request = jasmine.Ajax.requests.mostRecent(). You can then inspect request properties such as url, method, data().
To simulate the request succeeding and failing, use request.respondWith and pass in status codes and responseText bodies. A 200 status will simulate success; 4xx or 5xx range will go down the error path. You can then test your success and error functions do the right thing.