无法在Jasmine单元测试中窥探ajax的交错成功回调 [英] Not able to spyOn the interleaved success callback of an ajax in Jasmine unit testing
问题描述
在源代码中,我有一个getJSON调用,在以下结构中有两个成功回调。
In source code I have one getJSON call with two success callback in the following structure.
要测试的源代码:
jsonMakeLineOrderData = $.getJSON(url, jsonData,
function (data) {
console.log("Inside 1st callback");
//… some other statement
}).success(function (data) { // line# 1
console.log("Inside 2nd callback");
//… some other statement
});
我正在使用Jasmine测试框架测试此次调用的成功块。
I am using Jasmine testing framework to test the success blocks of this call.
假冒/模拟ajax调用我使用了spyOn实用程序。
To fake/mock the ajax call I have used spyOn utility.
我的Jasmine测试规范:
My Jasmine test spec:
it ("Test Function",function(){
var data = <json_data>;
var d;
spyOn($, "ajax").andCallFake(function(params) {
params.success(data); // line# 2
d = $.Deferred();
d.resolve(data);
return d.always();
});
});
在上面的示例中,我可以测试第一个回调,但无法测试第二个回调。
In the above example I am able to test the 1st callback but not able to test the 2nd callback.
由于测试规范中的第2行,第一个回调正在执行。
The 1st callback is executing due to line# 2 in the test spec.
我试图使用jQuery延迟实例来执行第二个回调,但是它抛出TypeError:$ .getJSON(...)。成功不是函数错误,如果我将 .success()语句更改为第1行的源文件中的 .done(),则测试用例正在运行很好,但我无法使用 .success(),不幸的是我不想更改源文件,所以我必须使用 .success()。
I have tried to use jQuery deferred instance to execute the 2nd callback but it is throwing "TypeError: $.getJSON(...).success is not a function" error, if I change the .success() statement to .done() in the source file at line # 1 the test case is working fine, but I am not able to make it work with .success(), unfortunately I am not suppose to change the source file, so I have to work with .success().
如果有人有任何解决方案,请告诉我。
If anybody has any solution please let me know.
提前致谢。
推荐答案
你必须返回一个函数来调用这样的回调函数:
You have to return a function that will call the callback like this:
it ("Test Function",function(){
var data = <json_data>;
spyOn($, "getJSON").andReturn({success: function(c){c(data)}});
});
为了更容易进行ajax测试,我建议 sinonJS ,它有一个简单的方法来使用虚假服务器来模拟ajax 。
For easier ajax testing I would advice sinonJS which has a simple way to mock the ajax with a fake server.
这篇关于无法在Jasmine单元测试中窥探ajax的交错成功回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!