Write simple tests with CasperJS

Automate stuff with ease

The first time I had interaction with computers, it was the graphic design that got me into this profession. Since early on I was curious about video games and how those visual elements were created and combined together to present a seamless story. When I started programming, testing felt very daunting to me. The reason perhaps is that this field has become complex and setting up tools to write even the simplest of tests is pretty complicated.  All I wanted was to validate if the story (program) I created is seamless or not. i.e. A simple way to automate some actions that a human being would take; provided the program is being built for a human. However, it was far from simple.

“CasperJs lets you write tests in simple Javascript”

Fortunately, with advancements in programming technologies and web in general, now it is very easy to write tests in JavaScript. Meet CasperJS, a simple API that lets you write your test in JavaScript. It is as simple as writing jquery.


There is only one requirement for this and that is a headless browser. A headless browser is basically just like a regular browser but it runs in the background so that your script can run on it without a GUI. I personally like PhantomJS.

PhantomJS is pretty easy to install, Download the file  based on the operating system you have and then run the executable


As always I recommend npm for the installation.

npm install casperjs

Once done, you can test if the setup was successful by running the following

node_modules/casperjs/bin/casperjs selftest


In this example, we’ll go to http://definedictionarymeaning.com/ and search for a term and then confirm if we have programmatically reached the search page.

var casper = require("casper").create();


casper.then(function() {
  this.echo("Job started at " + Date.now(), "INFO");
  this.sendKeys('input[id="search-input"]', "chicken");

casper.then(function() {
  // Click the search button

casper.then(function() {
    "Confirming if search page has been reached: new location is " + this.getCurrentUrl()


Dive Deeper

There is so much more we could do with this API like navigation & automation,  testing, and scraping.  We have barely scratched the surface here. I suggest you head over to CasperJS website and specifically look at their API docs section for more information and examples

Handy Code Snippets in CasperJS

Leave A Comment