Snippet: Using a config file for CapserJS and PhantomJS

Today’s Code Snippet is for using a JSON configuration file with CapserJS and PhantomJS.  I have been using JSON configuration files with my test automation for a while now to help manage test URLs, user agents, users, etc.  It is a great way to make your automation more flexible and update settings for an entire application.   Below is an example of how your configuration file would look.


    "PROD": {"url": ""},
    "QA1": {url": ""},
    "QA2": {url": ""}
    "IE11": "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko",
    "FF40": "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1",
    "Chrome": "Chrome/45.0.2454.101"

In this configuration we have the URLs for testing as well as several user agents to select from that you will then use in your script.

var env = casper.cli.get("envvar browser = casper.cli.get("browservar config = require('config.json');
var address = config["Environments"][env]["url"];
var agent = config["userAgents"][browser];
casper.test.begin('', function suite(test){
    casper.start(address, function firstStep(){

So what does it mean?

In the code of your test script, you’re setting up the variables to select inputs from the command line for “env” and “browser”.  These will be used for all of the tests you have in the test script.  Let’s look at how we’re getting the user agent information.

var browser = casper.cli.get("browserar agent = config["userAgents"][browser];

We took the variable of “browser” from the command line and are now using it to navigate through the configuration file to find the appropriate information to pass into our test setUp.  This will allow us to run all of our test with this user agent information.

The command to execute would look like this:

casperjs test tests/ –env=QA2 –browser=IE11 –ssl-protocol=tlsv1

Taking it further

The more that you put into your configuration file, the more options you have.  For instance, you could add to your user agent so that it includes viewpoint sizes.  This would be helpful for is you had a screen resolution minimum on your desktop site and for mobile device user agent settings.  I have included user account information in my configuration file where I include a setting in the environment section, such as “QA1″: {url”: ““, “type”: “test”}.  Then I would capture the type and use it for determining the password for the environment.  There are a number of ways to expand out your configuration file for testing.

What will you do with it?

Leave a Reply