问题
I am testing a code using jasmine and creating a mock object for ajax method
spyOn($,'ajax').and.callFake(function(e){
console.log("is hitting");
})
to test the following piece of code
$.ajax({
url: AppManager.defaults.contextPath + "/solutions/mcn/mcn-lookup-list",
data: {
mcnNumber : mcnNumberData,
mcnCustomerName : mcnCustomerNameData
},
dataType: "json",
type: "GET",
global: false
})
.done(function(data) {
solution.CommonObjects.theSolution.orderHandoff.mcnSearchData = self.filterMCNSearchData(data, resultObj);
$promise.resolve();
})
.fail(function() {
$promise.reject();
self.displayErrorPopup('MCN Search Error','There is no MCN associated with MCN Number or MCN Customer Name Entered!!!');
});
},
It's throwing an error cannot read done of undefined . Do I need to create a spy for that also . Please help with the code to do so
回答1:
Issues with your code:
- You are spying it right but you need to send in a
promise
object back via your spy. Basically you need to return something like this ==>return new $.Deferred().resolve(dummyData).promise();
- There are multiple ways to create a
deferred object/promise object
. I suggest you to read both Promise & Deferred - Also could you explain where your
$promise
is coming from? is this some feature ofrequire.js
?
Below is one way to fake the ajax calls.
var testObj = {
ajaxFunction: function() {
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/1'
}).done(function(data){
consoleLogFunction(data);
});
}
};
var consoleLogFunction = function(data){
console.log("The lengh of array is..=> "+ data.length);
};
describe("ajax test suite", function() {
it("expect true to be true", function() {
var dummyData = ["Foo", "Boo"];
spyOn($, 'ajax').and.callFake(function(e){
return new $.Deferred().resolve(dummyData).promise();
});
spyOn(window, 'consoleLogFunction').and.callThrough();
testObj.ajaxFunction();
expect(window.consoleLogFunction).toHaveBeenCalledWith(dummyData);
});
});
来源:https://stackoverflow.com/questions/41261559/ajax-test-code-throwing-error