javascript - 如何使用 jasmine 模拟 jquery getJSON 回调

标签 javascript jquery jasmine2.0

我有一个包含加载函数的模块,并且该加载函数调用 jQuery 的 getJSON 函数

load(key,callback){
  // validate inputs
  $.getJSON( this.data[key],'',function(d){
      switch(key){
        // do some stuff with the data based on the key
      }
      callback('success');
  });
}

使用 Jasmine 2.0,我如何模拟对 getJSON 的调用,但将数据提供给匿名函数?

最佳答案

我建议使用 Jasmine 的 ajax 插件,它可以模拟所有 AJAX 调用(getJSON 是一个 ajax 调用)。以下是如何执行此操作的示例:

//initialise the ajax mock before each test
beforeEach( function() { jasmine.Ajax.install(); });
//remove the mock after each test, in case other tests need real ajax
afterEach( function() { jasmine.Ajax.uninstall(); });

describe("my loader", function() {
   it("loads a thing", function() {
      var spyCallback = jasmine.createSpy();
      doTheLoad( "some-key", spyCallback );   //your actual function

      //get the request object that just got sent
      var mostRecentRequest = jasmine.Ajax.requests.mostRecent();

      //check it went to the right place
      expect( mostRecentRequest.url ).toEqual( "http://some.server.domain/path");

      //fake a "success" response
      mostRecentRequest.respondWith({
         status: 200,
         responseText: JSON.stringify( JSON_MOCK_RESPONSE_OBJECT );
      });

      //now our fake callback function should get called:
      expect( spyCallback ).toHaveBeenCalledWith("success");

   });
});

还有其他方法,但这个方法对我来说非常有效。更多文档在这里:

https://github.com/jasmine/jasmine-ajax

关于javascript - 如何使用 jasmine 模拟 jquery getJSON 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46309333/

相关文章:

jquery - 模态中的粘性标题和按钮

javascript - 我应该学习 ASP.NET AJAX、jQuery 还是两者都学?

javascript - 如何使用 jQuery 获取和设置图像

javascript - jasmine mockDate 总是休息一个月

javascript - 返回最大的数组

javascript - 滚动 DIV 元素的特定滚动条

javascript - 选择 onchange 本地存储在 Firefox 中不起作用

javascript - JS : Can "false" be type-coerced to false?

typescript - Jasmine 测试资源管理器未在 visual studio 代码中的 jasmine 测试资源管理器中显示测试用例(它阻止)列表

json - 如何在 Jasmine 中比较 json 对象