samedi 28 février 2015

Headless Browserify JavaScript Testing with Phantom.js

I'm trying to find a way to execute the following steps.



  • Write Node.js code for the browser

  • Compile the code with browserify

  • Test the browser code in the terminal


I would love to get the console.logs that the browser receives, but within the terminal. This would not only save me time (from creating a HTML file, running a server, opening a browser), it would also allow for cool things like automatic testing before deployment.


I'm trying to make something called headless-test.js a phantomjs script that would get passed an argument using system.args[1] and fs.read can get the contents of any javascript you pass to it.



var content = fs.read(system.args[1])
page.content = '<html><body><script type="text/javascript">'+content+'</script></body></html>'


That would allow me to do something like this:



phantomjs ./headless-test.js ./bundle.js


I was getting this error SyntaxError: Multiline comment was not closed properly so make sure you uglify your bundle.js.


All of this would be amazing and work if I could get this demo below working. The minimal viable product:



var system = require("system")
var webPage = require('webpage')
var page = require('webpage').create()
page.content = '<html><body><script type="text/javascript">console.log("hello world")</script></body></html>';

page.onConsoleMessage = function(msg, lineNum, sourceId) {
console.log('CONSOLE: ' + msg + ' (from line #' + lineNum + ' in "' + sourceId + '")');
};

page.evaluate(function(){

})

phantom.exit();


The expected results here are:



$ phantomjs ./headless-test.js
hello world


However I'm getting no stdout from phantom.


Aucun commentaire:

Enregistrer un commentaire