The first time I write such a test

I can not figure out how to make the right spy (spy), which will be called upon a successful ajax request.

Layout of the function to be tested:

testMe: function(param1, param2, fnSuccess, fnError) { ...Различная работа с переданными параметрами... $.ajax({ url: '/myUrl/', data: { "param1": param1, "param2": param2 }, success: fnSuccess error: fnError }); } 

It is necessary to transfer the spy as a callback to success (success) so that when it is executed, I get it in the "ok" test. It seems to me to try this one in various ways, closest to me (I publish it):

 var server = sinon.fakeServer.create(); var callback = sinon.spy(); lock.setLock(param1, param2, callback, function() {}); server.respond(); ok(callback.called); <--failed 

However, I get failed on exit

What am I doing wrong?

    1 answer 1

    intercept all XHR requests per page:

     var tempGlobal; function addXMLRequestCallback(callback) { var oldSend, i; if (XMLHttpRequest.callbacks) { XMLHttpRequest.callbacks.push(callback); } else { XMLHttpRequest.callbacks = [callback]; oldSend = XMLHttpRequest.prototype.send; XMLHttpRequest.prototype.send = function() { for (i = 0; i < XMLHttpRequest.callbacks.length; i++) { XMLHttpRequest.callbacks[i](this); } oldSend.apply(this, arguments); } } } addXMLRequestCallback(function(xhr) { console.log(xhr); }); 
    • A callback, I suppose, is sinon.spy? By the way, my test earned when I started using stub (sinon.stub ()) - Mr. Brightside
    • And, of course, no, I have a general solution, for sinon, it is really necessary to use internal means, stub - 11111000000
    • I liked this decision, so as not to lose, I even shove him somewhere =) - Mr. Brightside