我有一个CasperJS测试套件需要验证图像onload事件。为了验证这一点,我有一个1x1像素的GIF图片,这是我利用服务网络服务器PhantomJS:PhantomJS webserver的CasperJS测试无法加载本地图像
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
语句,并且他们显示我的路由有效,服务器确实收到了此调用,但看起来像git图像根本没有提供。 我试图用来自互联网的类似图像this one替换本地电话px.gif
,并通过测试!所以这个问题肯定涉及到PhantomJS web服务器如何提供本地gif图像。
是的,我知道casper的'resourceExists','waitForResource'等等。我有一个非常具体的测试用例可供参考。 – coquin