如何使用 jasmine 模拟 jquery getJSON 回调

How to use jasmine to mock jquery getJSON callback

我有一个包含加载函数的模块,该加载函数调用 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