问题
In source code I have one getJSON call with two success callback in the following structure.
Source code to test:
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
});
I am using Jasmine testing framework to test the success blocks of this call.
To fake/mock the ajax call I have used spyOn utility.
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.
The 1st callback is executing due to line# 2 in the test spec.
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.
Thanks in advance.
回答1:
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)}});
});
For easier ajax testing I would advice sinonJS which has a simple way to mock the ajax with a fake server.
来源:https://stackoverflow.com/questions/17575523/not-able-to-spyon-the-interleaved-success-callback-of-an-ajax-in-jasmine-unit-te