【问题标题】:Waiting in QUnit tests等待 QUnit 测试
【发布时间】:2011-11-18 14:37:08
【问题描述】:

我有 jQuery 代码,当我点击一个链接时,它首先隐藏然后删除一些 HTML,如下所示:

$(this).parent().parent().hide('slow', function () {
    $(this).remove();
});

我想进行 QUnit 测试,确保相关 HTML 已被删除:

$(thelink).click();

// Check that it is gone, by finding the first item in the list
entity = input.form.find('.recurrenceinput_occurrences .occurrence span.action a')[0];
// And make sure it's NOT the deleted one:
ok(entity.attributes.date.value !== "20110413T000000");

问题当然是 ok() 测试是在 hide 动画运行结束之前运行的,所以有问题的 HTML 还没有被删除,测试失败了。

我尝试了各种方法来延迟/停止测试一秒钟左右,但似乎没有任何效果。最明显的一个是使用 asynTest 并做

stop();
setTimeout(start, 2000);

但这实际上并没有停止测试。它似乎确实停止了 某事 两秒钟,但我不确定是什么。 :-)

有什么想法吗?

【问题讨论】:

    标签: javascript jquery qunit


    【解决方案1】:

    您的测试应该如下所示。

    test('asynchronous test', function() {
        stop(); // Pause the test 
        //Add your wait
        setTimeout(function() {
           //Make assertion 
           ok(true);
           // After the assertion called, restart the test
           start();
        }, 1000);
    });
    

    UPD: In QUnit 2.x functions start() and stop() are gone。建议改用assert.async()。更新后的代码如下:

        test('asynchronous test', function() {
            var done = assert.async();
            //Add your wait
            setTimeout(function() {
               //Make you assertion 
               ok(true);
               // Tell QUnit to wait for the done() call inside the timeout.
               done();
            }, 1000);
        });
    

    【讨论】:

    • 宾果游戏!这是正确的顺序。 :-) 所以 stop() 实际上只是阻止测试完成?
    • 这种方法已被弃用 (qunitjs.com/upgrade-guide-2.x/…)。 @ekcrisp 的回答使用了新方法。
    • 令人惊讶的是,6 年前提出的问题已被弃用。大声笑
    【解决方案2】:

    您可以使用promise 函数在元素的所有动画完成后触发回调。这意味着您需要知道在测试中动画在哪些元素上运行(但您不需要知道动画有多长)。

    【讨论】:

    • 这是一个有趣的想法,但我现在卡在 jQuery 1.4 上,所以没办法。
    【解决方案3】:

    使用你可以做的 QUnit 断言对象

    test("async test", function (assert) {
        var done = assert.async();
        setTimeout(function() {
                delayedPartOfTest();
                done();
            }, 20000);
        })
    
    });
    

    【讨论】:

      猜你喜欢
      • 2015-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多