简体   繁体   English

测试包含异步代码的功能

[英]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? 使用qUnit,我了解如果测试中包含异步代码,那么如何使用asyncTest() ,但是如果您具有包含异步代码的函数,该怎么办?

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? 如何在测试中调用makeAjaxCall() ,然后对从ajax请求返回的data进行测试?

You could use the jQuery Global Ajax Event Handlers in this situation. 在这种情况下,您可以使用jQuery Global Ajax事件处理程序 Bind it before calling, unbind it once you finish the test, possibly via the module method in Qunit. 在调用之前将其绑定,完成测试后即可取消绑定(可能通过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. 请注意,全局处理程序无权访问已解析的内容 ,而您必须使用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 ! 似乎没有人在乎mockAjax ,所以最近我发现了一些更好的东西: sinonJS Do you know the feature autoResponse of this wonderful tool named Fiddler ? 您知道这个名为Fiddler的出色工具的功能autoResponse吗? sinonJS allows you to do the same on the client side, it's a kind of ajax by-pass proxy. sinonJS允许您在客户端执行相同的操作,这是一种Ajax旁路代理。 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. 如果您有兴趣查看示例,请告诉我 ...以便sinonJS可以在不访问服务器的情况下响应任何ajax请求,如果您要模拟客户端,并且要对JavaScript代码进行单元测试,这就是一种魔术。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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