This technique of executing Selenium tests in non GUI mode is called headless testing. It is worth noting at this point that we’ll need to use GhostDriver for PhantomJS to work with Selenium. However, as GhostDriver comes integrated in latest versions of PhantomJS, we don’t need to configure it separately.
Without wasting any more time now, let’s configure PhantomJS with Selenium WebDriver. Since below mentioned steps are for Mac, setup may vary(albeit slightly) for other platforms. We have used Java as a choice of programming language for this setup.
Steps to use PhantomJS with Selenium:
- Download PhantomJS from here.
- Extract the downloaded ZIP file.
- Open Terminal window and navigate to ‘bin’ location of extracted directory.
- Run below command from terminal. Here 8989 is a port on which GhostDriver will run. You can change it as per your choice of port.
- Download PhantomJS JAR file from here and reference it in your project. If you are using Maven, you need to add below dependency in your Maven configuration file.
- Now, call PhantomJSDriver using below code. You will need to insert
import org.openqa.selenium.phantomjs.PhantomJSDriver; import statement for PhantomJSDriver to work.
driver = new PhantomJSDriver();
- Run your tests just as you would for any other browser!
There are many advantages of using PhantomJS with Selenium tests. Execution speed being the biggest one. And due to its speed, this setup proves ideal for continuous integration environment. Talking about its limitations, the obvious downside of PhantomJS is its WebKit-only compatibility. This is minor drawback considering majority of web applications are now WebKit compliant.
We hope the above setup of using PhantomJS with Selenium would prove useful in your automation testing activities. We would love to hear your feedback via comments.