dimanche 19 avril 2015

Jasmine: stub an ajax success call and pass the function an argument

I am looking to write a test in Jasmine that expects a string to be displayed in the browser when a button is clicked, that triggers an AJAX call returning a JSON object from an API which then has a function run on it, to extract the required data.


Using the Jasmine Ajax documentation I have come up with the following solution, which is working, but I have noticed a weakness in this test.



beforeEach(function(){
jasmine.getFixtures().fixturesPath = '.';
loadFixtures('thermostat.html');
});

describe("displaying weather from open weather map api", function() {

it("can display current temp for London", function(){
jasmine.Ajax.install();
var weatherobject = {"main": {"temp": 12.09}}
jasmine.Ajax.stubRequest('http://ift.tt/1mGUATE').andReturn({
success: loaddata(weatherobject)
});
$("#London").click();
expect("#weatherapidata").toContainHtml("12.09");
jasmine.Ajax.uninstall();
});
});


Below is the javascript and jQuery it is testing. If the function contents, in the success response, of this code, are changed to something other than loaddata the tests will still pass, as loaddata is also called in the test, as I could not work out how to pass the success function an argument of the weatherobject in the test.



$(document).ready(function(){

$('#London').click(function(){
$.ajax({
url: "http://ift.tt/1mGUATE",
data: {
q:"London",
units:"metric",
APPID: weatherapikey
},
success: function(data){
loaddata(data);
}
});
});
});

function loaddata(data) {
$("#weatherapidata").text(data.main.temp);
};


Therefore my question is; is it possible to construct the jasmine test stub to pass the data parameter of function in the success response an argument of the weatherobject?


My thoughts were to pass the object as a string in responseText, in the following way



jasmine.Ajax.stubRequest('http://ift.tt/1mGUATE').andReturn({
responseText: weatherobject
});


(I also tried JSON.stringify(weatherobject) as the responseText callback in this format) but I could not get this to work and hence my above solution was the workaround.


Aucun commentaire:

Enregistrer un commentaire