How to use CasperJS to automate website testing

CasperJS is a navigation scripting & testing utility for PhantomJS, written in Javascript. Its a pretty handy utility to automate functional testing of a website. I’ll use a wordpress site as an example to test presence of canonical url. More things like presense of closing html tag, footer being present, page size, etc. can be tested. This article is meant to be a quick start guide.

How to Install CasperJS on Mac

How to use CasperJS to test website

I’ll use casperjs to test if exactly one canonical url is present on a tag page and its value is correct. Here is the code to test that using CasperJS:

var links = [];

casper.start('', function() {

casper.then(function() {
  links = this.evaluate(function getLinks() {
    var links = document.querySelectorAll('link[rel=canonical]');
    return, function(e) {
      return e.getAttribute('href')
}); {
  this.test.assertEquals(links.length, 1, "Canonical link count is 1 as expected");
  this.test.assertEquals(links[0], '', "Correct canonical link");

Here run the above code using casperjs

$ casperjs test casper_canonical_test.js
PASS Canonical link count is 1 as expected
PASS Correct canonical link

You can also consider setting up a cron to run some of these tests daily and get the results in email.

CasperJS command – memory used

From above run, here is the outcome of ps (on Mac OS X 10.7.5):

user         21452   6.7  1.7   787708  72300 s005  R+    5:52PM   0:00.82 phantomjs /usr/local/Cellar/casperjs/1.0.2/libexec/bin/bootstrap.js --casper-path=/usr/local/Cellar/casperjs/1.0.2/libexec --cli casper_canonical_test.js

Note that the resident memory used is approx. 72M and virtual memory is approx 78M.

CasperJS pros and cons

PhantomJS uses webkit engine and render pages. So this way if there is any Javascript code on the page, that is also run. This will make it slower than using some other approach which does not render the page. At the same time, rendering makes it possible to even test javascript behavior.


Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit


Click here to write/view comments