Jasmine:存根ajax成功调用并传递函数参数

时间:2015-04-19 00:27:51

标签: javascript jquery ajax json jasmine

我希望在Jasmine中编写一个测试,希望在单击一个按钮时在浏览器中显示一个字符串,触发一个AJAX调用,从API返回一个JSON对象,然后在其上运行一个函数,到提取所需的数据。

使用Jasmine Ajax文档,我提出了以下解决方案,该方法正常运行,但我注意到此测试存在缺陷。

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();
  });
});

下面是它正在测试的javascript和jQuery。如果此代码的成功响应中的函数内容更改为loaddata以外的其他内容,则测试仍将通过,因为在测试中也会调用loaddata,因为我无法解决如何在测试中传递成功函数weatherobject的参数。

$(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);
};

因此我的问题是;是否可以构造jasmine测试存根以在成功响应中传递data function参数作为weatherobject的参数?

我的想法是将对象作为responseText中的字符串传递,方式如下

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

(我也尝试JSON.stringify(weatherobject)作为此格式的responseText回调)但我无法使其工作,因此我的上述解决方案是解决方法。

Github link to this project

我还添加到jsfiddle但是目前我找不到一个与jsfiddle配合使用的jasmine-jquery cdn,因此找不到' toContainHTML'抛出一个不是函数错误。但是,存根的响应可以在HTML顶部按钮上方的行中看到。

2 个答案:

答案 0 :(得分:3)

这篇blog帖子指导我使用一种略微不同的构建测试的方法,它通过向成功回调提供JSON对象来满足要求。通过监视ajax调用,然后使用mostRecent()来解决$("London").click() ajax函数上的成功回调,并为其提供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")
});

答案 1 :(得分:0)

我认为ajax存根会影响夹具加载过程(也使用ajax)。建议的解决方案是预加载灯具

https://github.com/velesin/jasmine-jquery#mocking-with-jasmine-ajax

这有帮助吗?

相关问题