检查图像是否正确加载Qunit [英] Checking if image properly loaded with Qunit

查看:124
本文介绍了检查图像是否正确加载Qunit的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过将网址设置为 Qunit 的图像网址 > src 测试图像的属性,并检查错误事件处理程序是否顺利。到目前为止我所拥有的是:

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

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

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

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.

推荐答案

通过快速浏览QUnit API,我发现你应该使用 asyncTest 这个功能。在为 test_image 设置src属性之前,将函数挂钩到 加载 事件。这是一个未经测试的代码:

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

这篇关于检查图像是否正确加载Qunit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆