Simple method to compare images on jasmine tests

Yesterday Danny and me were looking for method to include a comparison on a jasmine test using screenshots.

After some digging we came out with something like this:

First to run our jasmine tests and have some nice console output:

simple.js

// setup Jasmine 
const Jasmine = require('jasmine');
const jasmine = new Jasmine();

jasmine.loadConfigFile('spec/support/jasmine.json');

jasmine.jasmine.DEFAULT_TIMEOUT_INTERVAL = 15000;
 
// setup console reporter 
const JasmineConsoleReporter = require('jasmine-console-reporter');
const reporter = new JasmineConsoleReporter({
    colors: 1,           // (0|false)|(1|true)|2 
    cleanStack: 1,       // (0|false)|(1|true)|2|3 
    verbosity: 4,        // (0|false)|1|2|(3|true)|4 
    listStyle: 'indent', // "flat"|"indent" 
    activity: false
});
 
// initialize and execute 
jasmine.env.clearReporters();
jasmine.addReporter(reporter);
jasmine.execute();

And our tests is something like:

first.spec.js

var fs = require('fs');
var PNG = require('pngjs').PNG;
var pixelmatch = require('pixelmatch');

function are_different(original,baseline,diffname) {
  var data = fs.readFileSync(original);
  var img1 = PNG.sync.read(data);
  
  var data = fs.readFileSync(baseline);
  var img2 = PNG.sync.read(data);
  var diff = new PNG({width: img1.width, height: img1.height});
  var numberDifferent = 
  pixelmatch(img1.data, img2.data, diff.data, img1.width, img1.height, {threshold: 0.1});
  if (numberDifferent > 0) 
  {
    var options = { colorType: 6 };
    var buffer = PNG.sync.write(diff, options);
    fs.writeFileSync(diffname, buffer);
    return true;
  }
  return false;
}
  
describe("widget test", function() {
  var a;
  it("should open and look pretty", async function() {
      const puppeteer = require('puppeteer');
      const browser = await puppeteer.launch({headless:false});
      const page = await browser.newPage();
      await page.goto('file:///F:/jasmineParaTontos/index.html');
      await page.click("span.k-combobox span.k-i-arrow-60-down")
      await page.screenshot({path: 'example.png'});
      await browser.close();
      a = true;
      a = !are_different('example.png','exampleExpected.png','diff.png');
      expect(a).toBe(true);
  });
});

Using pixelmatch is simple does not require a lot of complicated packages and is fast.
:)