为了使用webdriver.io测试我的React应用,我需要使用phantomjs启动它。
起初我以为问题出在webdriver.io,但我意识到当我尝试渲染时PhantomJS返回一个空白页。
为了进行一些测试,我编写了这个javascript文件:
var page = require('webpage').create(); var args = require('system').args; var output_file = 'example.png', url = args[1]; t = Date.now(); var width = 1440; var height = 900; page.viewportSize = { width: width, height: height }; page.paperSize = { format: 'A4', orientation: 'landscape', margin: { left: '1cm', right: '1cm', top: '1cm', bottom: '1cm' } }; console.log(url); page.onConsoleMessage = function(msg, lineNum, sourceId) { console.log('CONSOLE: ' + msg + ' (from line #' + lineNum + ' in "' + sourceId + '")'); }; page.onLoadFinished = function (status) { window.setTimeout(function () { try { page.evaluate(function (w, h) { document.body.style.width = w + 'px'; document.body.style.height = h + 'px'; }, width, height); t = Date.now() - t; console.log('Loading ' + url); console.log('Loading time ' + t + ' msec'); page.clipRect = {top: 0, left: 0, width: width, height: height}; page.render(output_file); } catch (e) { status = e.message; } console.log(status + ';;' + output_file); phantom.exit(); }, 10000); }; try { page.open(url); console.log('loading'); } catch (ex) { console.log(ex.message); phantom.exit(); }
我这样启动: phantomjs test.js http://localhost:8080
phantomjs test.js http://localhost:8080
但是不管我做什么,example.png总是空虚。
example.png
我目前使用React 0.14.7和phantomjs 2.1.1。有人对我为什么无法渲染我的应用程序有任何想法吗?
PS:我没有提到,但我对chrome或firefox没问题
可能与PhantomJS中缺少ES6支持有关。为了检查,我在您的脚本中添加了page.onError()回调(总是很方便!),并打开了一些React示例站点来获取此错误:
ReferenceError: Can't find variable: Symbol
要填充符号,您可以在加载目标网址之前,将这个出色的包中的core.js脚本注入页面中:
page.onInitialized = function() { if(page.injectJs('core.js')){ console.log("Polyfills loaded"); } }
但这是为了打开外部站点。如果正在测试的站点处于开发中(如localhost url所建议的),则您可以只配置babel即可