Checking if image properly loaded with Qunit

社会主义新天地 提交于 2019-12-07 02:44:27

问题


I'm trying to validate image URLs with Qunit by setting the URL as the src attribute of a test image and checking with the error event handler whether that went well. So far what I have is:

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');
    }
});

My problem is that although the error event is properly triggered, it seems to occur in an asynchronous fashion and after the evaluation of is_valid (therefore whatever check I make, the result will always be the same). I have tried adding the ok() assertion inside the error event handler, but I'm getting the following error:

Error: ok() assertion outside test context

How can I run an assertion based on the processing performed inside the error event handler?

PS: if I insert a alert('test'); before checking is_valid it works fine (which confirms problem with error handler being asynchronous) but as you can imagine is not acceptable. I tried using setTimeout to delay execution of if statement but it brings the same assertion context error.


回答1:


By quickly looking through QUnit API, I see that you should use asyncTest function for this. Before setting the src-attribute for your test_image, hook a function to load event. Here's an untested code:

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');
});


来源:https://stackoverflow.com/questions/11776359/checking-if-image-properly-loaded-with-qunit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!