【发布时间】:2016-02-06 07:08:41
【问题描述】:
我有一个需要验证图像加载事件的 CasperJS 测试套件。为了测试这一点,我有一个 1x1 像素的 gif 图像,我使用 PhantomJS 网络服务器提供:
var fs = require('fs');
var webserver = require('webserver');
casper.test.begin('Image onload should be invoked', 1, {
setUp: function() {
var server = webserver.create();
this.server = server.listen(8080, function(request, response) {
if (request.url == '/') {
response.writeHead(200, { 'Content-Type': 'text/html' });
response.write('' +
'<!doctype html>\n' +
'<html>\n' +
'<head>\n' +
'<script type="text/javascript">\n' +
'window.onload = function() {\n' +
'var px = document.createElement("img");\n' +
'px.onload = function() {\n' +
'window._pxLoad = true;\n' +
'};\n' +
'px.src = "px.gif";\n' +
'};\n' +
'</script>\n' +
'</head>\n' +
'<body></body>\n' +
'</html>' +
'');
} else if (request.url.match(/px\.gif$/i)) {
response.writeHead(200, {
'Content-Type': 'image/gif',
'Cache-Control': 'no-cache'
});
var filePath = fs.workingDirectory + request.url.split('/').join(fs.separator).replace(/\d/gi, '');
response.write(fs.read(filePath));
}
response.close();
});
},
tearDown: function() {
this.server.close();
},
test: function(test) {
casper.start('http://localhost:8080', function() {
this.waitFor(function() {
return this.evaluate(function () {
return window._pxLoad !== undefined;
});
}, function then() {
var flag = this.evaluate(function () {
return window._pxLoad;
});
test.assertTruthy(flag, 'Image has been successfully loaded');
});
});
casper.run(function () {
test.done();
});
}
});
此测试失败,因为 window._pxLoad !== undefined 未在 5000 毫秒超时内进行评估。我什至在图像处理程序中放置了console.log 语句,它们表明我的路由有效,服务器确实收到了这个/px.gif 调用,但看起来根本没有提供 git image。
我尝试用来自互联网的类似图像this one 替换对本地px.gif 的调用,测试通过了!所以问题肯定与 PhantomJS 网络服务器如何提供本地 gif 图像有关。
【问题讨论】:
-
是的,我知道 casper 的
resourceExists、waitForResource和其他人。我有一个非常具体的测试用例要介绍。