检查图像是否正确加载Qunit

Max*_*Max 7 javascript jquery image qunit

我试图验证图像URLsQunit通过设置URL作为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');
    }
});
Run Code Online (Sandbox Code Playgroud)

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

Error: ok() assertion outside test context
Run Code Online (Sandbox Code Playgroud)

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

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

val*_*ion 8

通过快速查看QUnit API,我发现你应该使用asyncTest函数.在为您设置src属性之前test_image,将函数挂钩到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');
});
Run Code Online (Sandbox Code Playgroud)