Posted

2 minutes read

Jest is a complete and easy to set-up JavaScript testing solution which also provide a Snapshot Testing built-in mechanism.

With the Snapshot Testing functionality you can capture snapshots of React trees or other serializable values to simplify testing and to analyze how state changes over time.

In this article we are going to take advantage of Jest functionality to take screenshots of web pages using Puppeteer and compare generated screenshots with screenshots baseline in order to find regressions in the UI of any web page.

Jest is very easy to use with Puppeteer due to its Global Setup/Teardown and Async Test Environment APIs. More details on using Puppeteer to do visual regression testing can be found here.

With Puppeteer you can choose whether to launch Chromium in headless mode or not (tests run faster in headless mode, but it’s useful to be able to see the browser and run the test in slow motion for debugging purposes).

Prerequisites for your test to be able to run Jest tests with Puppeteer in order to take and compare screenshots of your web pages:


npm install --save-dev jest jest-cli

npm install --save-dev puppeteer

npm i --save-dev jest-image-snapshot

Here is an example on how to use Jest Image Snapshot:

  • Extend Jest’s expect assertion mechanism:

Example: Jest screenshot test


const { toMatchImageSnapshot } = require('jest-image-snapshot');

expect.extend({ toMatchImageSnapshot });

Example: Jest screenshot test with Puppeteer and Jest Image Snapshot with Headless Chrome



export const browserConfig = {
ignoreHTTPSErrors: true,
headless: true,
args: ['--no-sandbox', '--disable-setuid-sandbox'],
};

// jest-image-snapshot custom configuration in order to save screenshots and compare the with the baseline
export function setConfig (filename) {
return {
failureThreshold: '0.01',
failureThresholdType: 'percent',
customSnapshotsDir: `${__dirname}/../snapshots/`,
customSnapshotIdentifier: filename,
noColors: true
}
}

describe('screenshot', () => {
let browser;

beforeAll(async () => {
// start Puppeteer with a custom configuration, see above the setup
browser = await puppeteer.launch(browserConfig);
});

it('dummy application page', async () => {
const page = await browser.newPage();

expect.extend({ toMatchImageSnapshot });
await page.goto('http://localhost:3000');
await page.setViewport({ width: 1280, height: 1400 });

const image = await page.screenshot({ fullPage: true });
expect(image).toMatchImageSnapshot(setConfig('image-name'));
}, 15000);

afterAll(async () => {
await browser.close();
});
});

Also, you can automate your visual regression testing by using our built-in visual regression testing service.