如何使用jasmine来模拟jquery getJSON回调

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

Interesting Posts