检查图像是否正确加载Qunit

时间:2012-08-02 11:20:19

标签: javascript jquery image qunit

我正在尝试使用URLs验证图片Qunit,方法是将网址设置为测试图片的src属性,并使用error事件处理程序进行检查顺利。到目前为止我所拥有的是:

test('image',function() {
    var test_image = $('#test-image');
    test_image.error(function(e) { // properly triggered
        console.log(e);             
        is_valid = false;
        // ok(false,'Issue loading image'); breaks qunit
    });
    var is_valid = true;
    test_image.attr('src','doesntexist');
    console.log('checking is_valid');  // occurs before error event handler
    if (is_valid) {  // therefore always evaluates to the same
        ok(true,'Image properly loaded');
    } else {
        ok(false,'Issue loading image');
    }
});

我的问题是虽然error事件被正确触发,但它似乎以异步方式发生并且在评估is_valid之后(因此无论我做什么检查,结果将始终是相同)。我尝试在ok()事件处理程序中添加error断言,但是我收到以下错误:

Error: ok() assertion outside test context

如何根据error事件处理程序中执行的处理运行断言?

PS:如果我在检查alert('test');之前插入is_valid它工作正常(这证实错误处理程序是异步的问题),但你可以想象是不可接受的。我尝试使用setTimeout来延迟if语句的执行,但它带来了相同的断言上下文错误。

1 个答案:

答案 0 :(得分:8)

通过快速查看QUnit API,我发现您应该使用asyncTest函数。在为test_image设置src属性之前,请将函数挂钩到load事件。这是一个未经测试的代码:

asyncTest('image',function() {
    var test_image = $('#test-image');
    test_image.error(function(e) {
        console.log(e);             
        ok(false,'Issue loading image');
        start();
    });
    test_image.load(function() {
        ok(true,'Image properly loaded');
        start();
    });
    test_image.attr('src','doesntexist');
});