【问题标题】:Simple Jasmine Async Test with Inverted waitsFor带有倒置 waitsFor 的简单 Jasmine 异步测试
【发布时间】:2013-12-06 20:43:03
【问题描述】:

我正在尝试编写一个我以前从未做过的异步测试。用英语测试是这样说的:

  • 使用回调创建计时器对象
  • 如果要启动定时器,它会在 500 毫秒后触发
  • 计时器不应启动
  • 等待 1000 毫秒并检查是否调用了回调,以确认未调用回调

所以,通过阅读文档和查看其他代码,我认为我应该这样写。

it("should create a timer not start", function (done) {
    var fail = false, timer;

    // if this test is passing, this should do nothing
    runs(function(){
        timer = new Timer(function () {
            fail = true;
            timer.pause();
        }, 500);
    });

    // if this test is passing, fail should never be true
    waitsFor(function(){
        return fail;
    }, 1000);

    // this should be called after 1 second because the previous times out
    runs(function(){
        expect(fail).toBeFalsy();
    });
});

但是 waitsFor 超时,因为 fail 永远不应该为真。我需要 waitsFor 等待一整秒,然后期望语句可以运行,但我需要超时是一件好事,而不是失败(Jasmine 将其报告为)。

我该如何使用 Jasmine?

【问题讨论】:

  • 已发帖或发表评论请注明正确答案。

标签: javascript unit-testing asynchronous jasmine


【解决方案1】:

编辑 2017-07-24
根据@Yavin5 的评论,此答案对 Jasmine v1 有效。

要升级到 Jasmine v2,请参考文档。 https://jasmine.github.io/2.0/upgrading.html#section-9

有关 Jasmine V2 文档,请访问 https://jasmine.github.io/2.0/introduction.html#section-Asynchronous_Support

您需要添加一个标志,该标志将在异步操作完成后变为真。这就是waitsFor 正在等待的东西。我会建议像

it("should create a timer not start", function (done) {
    var fail = false, timer, flag;

    // if this test is passing, this should do nothing
    runs(function(){
        flag = false;
        timer = new Timer(function () {
            fail = true;
            timer.pause();
        }, 500);
        setTimeout(function() {
        flag = true;
      }, 1000);
    });

    // if this test is passing, fail should never be true
    waitsFor(function(){
        return flag;
    }, 1100);

    // this should be called after 1 second because the previous times out
    runs(function(){
        expect(fail).toBeFalsy();
    });
}); 

【讨论】:

  • 大家都知道,这已经过时了,显然从 Jasmine 2.0.0 起已弃用(当我在 Jasmine 2.6.0 上尝试它时不起作用)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-03
  • 1970-01-01
  • 1970-01-01
  • 2017-06-01
  • 2018-09-10
相关资源
最近更新 更多