Jasmine: close the ajax success call and pass the function to the argument

I want to write a test in Jasmine that expects a string to be displayed in a browser when a button is pressed that calls an AJAX call that returns a JSON object from the API, which then performs a function on it to retrieve the required data.

Using the Jasmine Ajax documentation, I came up with the following solution that works, but I 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://api.openweathermap.org/data/2.5/weather').andReturn({
      success: loaddata(weatherobject)
    });
    $("#London").click();
    expect("#weatherapidata").toContainHtml("12.09");
    jasmine.Ajax.uninstall();
  });
});

Below is the javascript and jQuery that it is testing. If the contents of the function in response to the success of this code are changed to something else, the loaddatatests will pass anyway, since the test is also called loaddatabecause I could not figure out how to pass the Success function serves as an argument weatherobjectin the test.

$(document).ready(function(){

  $('#London').click(function(){
    $.ajax({
      url: "http://api.openweathermap.org/data/2.5/weather",
      data: {
        q:"London",
        units:"metric",
        APPID: weatherapikey
      },
      success: function(data){
        loaddata(data);
      }
    });
  });
});

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

: , data function weatherobject?

, responseText

jasmine.Ajax.stubRequest('http://api.openweathermap.org/data/2.5/weather').andReturn({
  responseText: weatherobject
}); 

( JSON.stringify(weatherobject) responseText ), , .

Github

jsfiddle, jasmine-jquery cdn, jsfiddle, , , toContainHTML 'throws a . HTML.

+4
2

blog , , JSON . ajax, mostRecent(), ajax $("London").click() JSON. , :

it("can send a GET request for weather data", function(){
  spyOn($, 'ajax');
  var weatherobject = {"main" : {"temp" : 12.09}}
  $("#London").click();
  $.ajax.calls.mostRecent().args[0].success(weatherobject);
  expect("#weatherapidata").toContainHtml("12.09")
});
+3

All Articles