Async controlled exit from phantomjs

I'm trying to do some testing using phantomjs ... basically I want:

  • open page on my web server
  • after page initialization (all js pages loaded)
  • call the js page from phantomjs and check the results
  • exit phantomjs

It seems difficult if phantoms notice when the page has loaded.

I could use phantomjs to set a β€œtest” variable in a window or something so that the js page can check this and then call a callback after it is complete. The problem is that the callback can only be a page callback, so it cannot do anything that the page could not do.

This may be good for tess, but the last step is not possible.

I came up with this:

page.onConsoleMessage = function(msg) { if (msg == "__quit__") { phantom.exit(); } else { console.log("page: " + msg); } }; page.evaluate(function () { window.quit = function () { console.log("__quit__"); }; }); 

That way, the page code can call window.quit (), and the console monitor can then kill phantom. It seems a bit hacked. Anyone have a better way to do this?

+8
javascript asynchronous testing phantomjs
source share
1 answer

Disclaimer: This is an unverified code.

You might be able to connect to the onLoadFinished callback of the webpage object. This is done in the PhantomJS scope, so you can use all of your variables.

Something like this should be enough:

 page.onLoadFinished = function(){ page.evaluate(function() { //call your testing code here }); phantom.exit(); } 
+1
source share