检查图像是否正确加载Qunit
我正在尝试使用Qunit
validation图像URLs
, Qunit
是将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
之前它工作正常(这证实error handling程序是异步的问题),但你可以想象是不可接受的。 我尝试使用setTimeout
来延迟if语句的执行,但它带来了相同的断言上下文错误。
通过快速浏览QUnit API,我发现你应该使用asyncTest
函数。 在为test_image
设置src-attribute之前,挂钩一个函数来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'); });