mocking xhr calls in Jasmine

我的未来我决定 提交于 2019-12-12 03:37:45

问题


I have a question regarding mocking xhr in Jasmine. I have the following Javascript situation:

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

Now I want to spyOn the xhr.getResponseHeader() function but I can not find out how I could do that.

I tried something like this:

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

But that did not work. Any ideas? Perhaps important to note. I use jQuery 1.8.


回答1:


The SinonJS library allows you to create fake XMLHttpRequests and responses so you can verify that the request is formed correctly and your code is dealing with the response correctly. A simple example to illustrate the basic technique:

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


来源:https://stackoverflow.com/questions/37454372/mocking-xhr-calls-in-jasmine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!