簡體   English   中英

檢查圖像是否正確加載Qunit

[英]Checking if image properly loaded with Qunit

我正在嘗試使用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');
    }
});

我的問題是雖然error事件被正確觸發,但它似乎以異步方式發生並且在評估is_valid (因此無論我做什么檢查,結果總是相同的)。 我已經嘗試在error事件處理程序中添加ok()斷言,但是我收到以下錯誤:

Error: ok() assertion outside test context

如何根據error事件處理程序內部執行的處理運行斷言?

PS:如果我插入alert('test'); 在檢查is_valid之前它工作正常(這證實錯誤處理程序是異步的問題),但你可以想象是不可接受的。 我嘗試使用setTimeout來延遲if語句的執行,但它帶來了相同的斷言上下文錯誤。

通過快速瀏覽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');
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM