Unit testing the success function of an ajax call in a Jquery plugin using Jasmine framework
In unit testing of the jQuery AJAX calls with Jasmine I usually can get by with spying on the success function before passing the options to the $.ajax() function (there are many examples on the net and on this forum about that).
however this time I had a peculiar problem. the options sent to $.ajax where buried deeply inside a jQuery plugin and created by a complex logic, and I my only way to get to the success function was to spy on $.ajax itself and call a fake function.
But now that I had the options, I couldn't call the $.ajax function anymore. so after a lot of web searching and API doc reading this is what I 开发者_开发知识库finally came up with to get the data which will come back from the server:
it('is going to steal the data returned from the server by ajax',function(){
var ajaxspy=spyOn($,'ajax');
ajaxspy.andCallFake(function(options){
ajaxspy.mysterious_options=options;
});
$(myelement).myjQueryPlugin(my_method_which_will_call_ajax_eventually);
spyOn(ajaxspy.mysterious_options,'success').andCallFake(function(data){
ajaxspy.stolen_data=data;
});
ajaxspy.andCallThrough();
ajaxspy.plan(ajaxspy.mysterious_options);
waitsFor(function(){
return ajaxspy.stolen_data;
})
runs(function(){
expect(data).toHaveSomeProperties();
})
}
Given that there is no way to intercept the options any spy on options.success() before $.ajax is called, could this be done simpler?
Thanks,
Reza
精彩评论