我正在尝试验证图像URLs
with 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
(因此无论我做什么检查,结果总是相同的)。我尝试过添加ok()
里面的断言error
事件处理程序,但我收到以下错误:
Error: ok() assertion outside test context
如何根据内部执行的处理运行断言error
事件处理程序?
PS:如果我插入一个alert('test');
检查之前is_valid
它工作正常(这证实了错误处理程序是异步的问题),但正如您可以想象的那样,这是不可接受的。我尝试使用setTimeout
延迟 if 语句的执行,但它会带来相同的断言上下文错误。
通过快速查看 QUnit API,我发现您应该使用asyncTest http://api.qunitjs.com/asyncTest/为此功能。在设置 src 属性之前test_image
,挂钩一个函数load http://api.jquery.com/load-event/事件。这是未经测试的代码:
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');
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)