Comparing image with a capture with CasperJS

Reading time ~1 minute

Last thursday I had the pleasure to give a workshop about CasperJS at SpainJS. You could get the presentation and the code samples here. At the end of the workshop an attendant asked me if it's possible to compare a capture with a reference image. My first answer was no. I was wrong. In this article we will see how we can accomplish this.

The idea, and the code, is super simple. Read both images and compare the bytes. Let's start casper, include the file system library and go to the page we want to capture:

var casper = require('casper').create({
	viewportSize: {
		width: 1024,
		height: 768
	}
});

var fs = require('fs'); 

casper.start('http://www.plainconcepts.com');

Now, we have to read the reference image, make a capture of the page and read the captured image to be able to compare with the reference one:

casper.then(function(){
	var referenceImageContent = fs.read('./plainconceptsOld.png');

	this.capture('plainconcepts.png');
	var newImageContent = fs.read('./plainconcepts.png');

	this.test.assert(newImageContent == referenceImageContent);
});

And finally, call to run function:

casper.run(function(){
	this.echo('finished');
	this.test.done(1);
	this.test.renderResults(true);
});

If you execute the code with the right reference image you will get this result:

[caption id="attachment_101" align="alignleft" width="720"]test passed test passed[/caption]

 

 

 

 

If you make a change in a single pixel of the image, then you will get this result:

[caption id="attachment_102" align="alignleft" width="719"]test faiiled test failed[/caption]

 

 

 

 

 

 

 

And that's all! Now you could compare a capture with a reference image. Remember that you can also capture a selector using captureSelector function.

 

Analysing hotspots using CrystalGazer and NDepend

When you start working on a new project, there are a couple of things that you should try to discover as fast as you can: the shape of th...… Continue reading

ANTLR and JavaScript

Published on September 06, 2017

Calling a Step Function

Published on July 09, 2017