测试包含异步代码的功能 [英] Testing for a function that contains asynchronous code

查看:52
本文介绍了测试包含异步代码的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用qUnit,我了解如果测试中包含异步代码,那么如何使用 asyncTest(),但是如果您具有包含异步代码的函数怎么办?

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.

以下面的代码为例:

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

如何在测试中调用 makeAjaxCall(),然后对从ajax请求返回的 data 进行测试?

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

推荐答案

您可以使用在这种情况下的jQuery Global Ajax事件处理程序.调用前先进行绑定,一旦完成测试,可以通过Qunit中的模块方法将其解除绑定.

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

请注意,全局处理程序无法访问已解析的内容,您必须使用JSON.parse自己重新解析它们.不理想,但我不知道另一种方式.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆