Visual Regression Testing With PhantomCSS & CasperJS: Part 2

Tags: quality assurance, Software testing

In the first part of this series, we discussed how to set up PhantomCSS and CasperJS, and we ran a basic test.

In this part, we shall discuss each section of a CasperJS test, and customizing PhantomCSS, CasperJS and relevant functions required in basic visual regression tests.

Below are the customizations and functions we will generally need in a test case. For a basic test structure, please refer to Part 1 of Visual Regression Testing with PhantomCSS and CasperJS.

1. Customizing PhantomCSS


   //mention the folders for the particular test case

   screenshotRoot: '/var/qa/screenshots/mytest',

   failedComparisonsRoot: './failures/mytest',

   comparisonResultRoot: './results/mytest',

   //customize the mismatch tolerance level for a specific test

   //there are videos and dynamic content on the page    

   mismatchTolerance: 0.50,

   rebase: casper.cli.get('rebase')


2. Initialize Phantom web page instance

start() creates and initializes a Phantom web page instance, and initializes the resources array, history and logs. Generally, one should use start() first and then proceed to using the then*() functions family.


3. Adding steps to the stack

Next, you can start using the then*() functions. Refer to thenOpen() will add steps to the stack.

casper.thenOpen('', function() {

 this.fill('form#user-login', {

  'name': 'admin',

  'pass': ‘password’

   }, true);



4. Adding a wait step

Add a wait function to allow the page to load completely before taking a screenshot for comparison. Here, 1000 = 1 second.  

casper.wait(2000, function() {

 this.echo("I've waited for 2 seconds.");


5. Defining the viewport size

By declaring the viewport size, we can take screenshots for different screen sizes (eg: iPhone, iPad, tablet, smartphone, etc).

casper.viewport(1024, 768);

6. Taking a screenshot for the body and elements on the page

//Function to take a screenshot for the body

  casper.then(function() {

     // take the screenshot of the whole body element and save it

     // under "mytest.png" the first parameter is the CSS selector

      phantomcss.screenshot('body', ‘mytest’);



//Similarly, to take a screenshot for a particular element, specify the css-selector as below:

  casper.then(function() {

     // take the screenshot of the CSS selector under test.        phantomcss.screenshot(‘css-selector’, `elementname`);


We hope you’ve found this post helpful. Leave a comment below if you have any questions!

Trupti Sawant & Avni Gupta
Posted by

Trupti Sawant & Avni Gupta