在Jasmine嘲笑xhr

我有一个关于在Jasmine中嘲笑xhr的问题。 我有以下Javascript情况:

function Test1(){ // some code Test2({ readyState: 4, responseText: "", status: 200, statusText: "OK" }); } function Test2(xhr){ var token = xhr.getResponseHeader("csrftoken"); var csrfCtrl = $("#token"); if (token != null && csrfCtrl != null) { csrfCtrl.val(token); } } 

现在我想窥探xhr.getResponseHeader()函数,但我无法知道如何做到这一点。

我试过这样的事情:

 describe("1 || Test ||", function () { // Before we describe the tests we first need to setup a few things beforeEach(function () { // Load the first function of the HTML fixtures (htmlfixtures.js) setUpHTMLFixture1(); jQuery.xhr = spyOn(jQuery.fn.ajax.xhr, "getResponseHeader").and.returnValue("null"); }); it("1.1 # Check xhr functionality", function () { expect(jQuery.xhr).toHaveBeenCalled(); }); }); 

但那没用。 有任何想法吗? 也许重要的是要注意。 我使用jQuery 1.8。

SinonJS库允许您创建虚假的XMLHttpRequests和响应,以便您可以validation请求是否正确形成,并且您的代码正确处理响应。 一个简单的例子来说明基本技术:

 var xhr, requests; beforeEach(function () { xhr = sinon.useFakeXMLHttpRequest(); requests = []; //when an ajax request is created it will be added to the requests array //rather than actually being sent xhr.onCreate = function (request) { requests.push(request); }; }); it("1.1 # Check xhr functionality", function () { var callback = sinon.spy(); //the code that is actually executing the ajax request called here $.ajax('/some/uri', { success: callback }); //give the fake response to the request sent above requests[0].respond(200, { "Content-Type": "application/json" }, '[{ "some": "testData" }]'); //assert some expectations expect(requests.length).toBe(1); expect(requests[0].url).toBe('/some/uri'); expect(callback.calledWith([{ some: "testData" }])).toBe(true); }); afterEach(function () { xhr.restore(); });