我推荐使用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
退房间谍https://jasmine.github.io/2.0/introduction.html#section-Spies –