简体   繁体   中英

Testing for a function that contains asynchronous code

With qUnit, I understand how to use asyncTest() if you have asynchronous code within your tests, but what if you have a function that contains asynchronous code?

In other words, the asynchronous request is not within the test, but is simply part of the code that is being tested.

Take this code for example:

function makeAjaxCall(){
    $.get('/mypage', {}, function(data){
        // Do something with `data`
    },'json');
}

How can I call makeAjaxCall() within a test and then run tests on the data that is returned from the ajax request?

You could use the jQuery Global Ajax Event Handlers in this situation. Bind it before calling, unbind it once you finish the test, possibly via the module method in Qunit.

Something like (untested):

asyncTest(function() {
  expect(1);

  $(document).ajaxSuccess(function(e, xhr, settings) {
     var jsonRep = JSON.parse(xhr.responseText);
     // assert on jsonRep
     //ok(true);
  });
  $(document).ajaxError(function(e) {
     ok(false);
  });
  $(document).ajaxComplete(function() {
     start();

     $(document).unbind('ajaxSuccess ajaxError ajaxComplete');
  });

  makeAjaxCall();
});

Note that the global handlers do not have access to the parsed contents , and you have to reparse them yourself using JSON.parse. Not ideal, but I don't know of another way.

It seems that nobody cares about mockAjax , so I found something better these days: sinonJS ! Do you know the feature autoResponse of this wonderful tool named Fiddler ? sinonJS allows you to do the same on the client side, it's a kind of ajax by-pass proxy. if you are interested to see an example, let me know ... so sinonJS can respond to any ajax request without accessing the server, that's kind of magic if you want to mock your client, if you want to unit test your javascript code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM