Ajax测试代码抛出错误 [英] Ajax test code throwing error
本文介绍了Ajax测试代码抛出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用jasmine测试代码并为ajax方法创建模拟对象
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");
})
来测试以下代码
$.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
推荐答案
您的代码问题:
- 你正在监视它,但是你需要通过你的间谍回复
promise
对象。基本上你需要返回这样的东西==>返回新的$ .Deferred()。resolve(dummyData).promise();
- 有多种方法可以创建
延迟对象/承诺对象
。我建议你阅读承诺
&延期
- 您还可以解释一下
$ promise
的来源吗?这是require.js的一些功能
?
- 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 bothPromise
&Deferred
- Also could you explain where your
$promise
is coming from? is this some feature ofrequire.js
?
以下是一种方法伪造ajax调用。
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);
});
});
这篇关于Ajax测试代码抛出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文