我推薦使用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 –