2016-05-26 83 views
0

我有一個關於嘲笑茉莉花xhr的問題。我有以下的Javascript情況:嘲笑xhr呼叫茉莉花

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); 
    } 
} 

現在我想spyOn的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。

回答

1

SinonJS庫允許您創建假的XMLHttpRequests和響應,以便您可以驗證請求是否正確形成,並且您的代碼正確處理響應。一個簡單的例子來說明基本技術:

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(); 
}); 
+0

謝謝!這會幫助我很多! :) – Rotan075