Run Selenium tests on headless browser

I’ve recently been using an open source driver called PhantomJS, which is a headless browser and supports Javascript, to execute my automated tests.

What is a headless browser?
A headless browser works just like the ‘normal’ browsers you would use on a day to day basis (for example Chrome or Firefox), just without a Graphical User Interface (GUI). This basically means the you would not see any content on the screen as there is no GUI.

Benefits of a headless browser?
If you’ve ever ran an automated test you would have noticed it becomes distracting after a few minutes as your browser opens and takes up most your screen and attention. The headless browser eliminates this as there is no GUI, allowing you to focus on other work while your test is running in the background.
Some say by using a headless browser test execution can be reduced by up to 50%, albeit I have not really seen much of a difference in terms of speed.

Are there many headless browsers?
The most common headless browsers I came across are:
HtmlUnit, PhantomJS, Ghost, and Watir.

In order to get your tests to run with PhantomJS you will need to change your driver, so it uses PhantomJSDriver instead of your existing driver which is likely to be either FirefoxDriver (WebDriver driver = new FirefoxDriver();) or ChromeDriver (WebDriver driver = new ChromeDriver();).

You can do this using the following code:

DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS, new String[] {“–web-security=no”, “–ignore-ssl-errors=yes”});
WebDriver driver = new PhantomJSDriver(caps);

The line of code below is very important as it allows PhantomJSDriver to work on websites which are HTTP as well as HTTPS. Without this you would be able to go to but you would not be able to go to

caps.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS, new String[] {“–web-security=no”, “–ignore-ssl-errors=yes”});