如何使用jasmine来测试需要很长时间才能响应的异步函数? [英] How to use jasmine to test an async function that takes a long time to respond?

查看:129
本文介绍了如何使用jasmine来测试需要很长时间才能响应的异步函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个函数从webapi获取数据。基本上使用 $ .ajax

I'm using a function to fetch data from webapi. Basicly using $.ajax.

我现在用等待测试它等待() 像这样:

describe('xxxxxxxxxxxxxxxxxxxxx', function () {
  var r;
  it('fetchFilter', function () {
    runs(function () {
      model.fetch(opts)
      .done(function(data) {
        r = data;
      });
    });

    waits(2000);

    runs(function () {
      expect(r[0].gender).toBeDefined();
    });
  });
});

问题是:


  1. 不能保证等待(2000)能很好地完成工作。由于各种原因(网络连接,api自身的算法效率等),我可能必须等待(5000)或更多,或者对于某些型号等待(500)就足够了。而最烦人的事情是它完全失控。

  2. 很多等待()使测试规范运行浪费了很多时间等待。运行整个套件的时间太长,无法接受。

  1. It's not guaranteed that waits(2000) will do the job well. Due to various reasons(network connections, algorithm efficiency of the api it self, etc.), I may have to waits(5000) or more, or for some models waits(500) is enough. And the most annoying thing is that it's all out of control.
  2. A lot of waits() makes the test-specs-runs waste a lot of time waiting. The time of running the whole suite is too long to accept.

是否有一些最佳实践做那些事情?

Is there some best practice of doing there kind of things?

PS:我知道单元测试不应该应用于某些依赖webapi或数据库的函数。但我正在使用单页js-heavy-webapp。数据获取过程与我将如何使用js模型一样重要。

PS: I know that unit test should not be applied to some function that relies on webapi or database. But I'm working with a single-page-js-heavy-webapp. The data fetching process is as important as how I will consume them with js models.

推荐答案

waitsFor( )将等待指定的latch回调返回 true (它将每隔几毫秒尝试很多次)。如果超过指定的超时(在这种情况下为5000毫秒),它也会引发异常。

waitsFor() will wait for a specified latch callback to return true (it will try many time every few ms). It will also raise an exception if the specified timeout (5000ms in this case) is exceeded.

describe('xxxxxxxxxxxxxxxxxxxxx', function () {
  var r, fetchDone;

  it('fetchFilter', function () {

    runs(function () {
      model.fetch(opts).done(function(data) {
        r = data;
        fetchDone = true;
      });
    });

    waitsFor(function() { 
      return fetchDone; 
    }, 5000); 

    runs(function () {
      expect(r[0].gender).toBeDefined();
    });

  });
});

检查 Jasmine docs 了解更多关于的信息waitsFor() runs()

这篇关于如何使用jasmine来测试需要很长时间才能响应的异步函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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