What is visual regression testing in puppeteer?

In visual regression testing, we are concerned with preventing unintentional changes to our application’s visuals. You will need to have a screenshot of what your user interface (UI) needs to look like to the user, and you will automatically run tests on the current UI to see if any “regression” has taken place.

In this shot, you will see how to perform visual regression testing with puppeteer and jest.

Setup

For this shot, we will be using puppeteer to control the browser and jest to run test cases. We will also use jest-image-snapshot, which is a great extension to jest for image comparisons.

Let’s go ahead and install them:

npm install --save-dev puppeteer jest jest-image-snapshot

Taking screenshots

For visual regression testing, we need screenshots of the UI. Let’s use puppeteer to navigate to the website and take a screenshot:

const puppeteer = require('puppeteer');
(async () => {
   const browser = await puppeteer.launch();
   const page = await browser.newPage();
   await page.goto('https://example.com');
   await page.screenshot({path: 'example.png'});
   await browser.close();
})();

Writing test cases

Writing test cases in jest is quite straightforward; we use describe for each test suite and it for each test. beforeAll and afterAll allows us to set up the browser and clean up before and after each test.

const puppeteer = require('puppeteer');

describe('visual reg. test', () => {
   let browser;
   beforeAll(async () => {
      browser = await puppeteer.launch({ headless: false })
   });
   it('test case', async () => {
      // example test case
   });   
   afterAll(async () => {
      await browser.close();
   });
});

Visual regression testing

Finally, we can combine the puppeteer and jest code and add jest-image-screenshot for visual regression testing:

const puppeteer = require('puppeteer');
describe('visual reg. test', () => {
let browser;
beforeAll(async () => {
browser = await puppeteer.launch({ headless: false })
});
it('testing homepage', async () => {
const page = await browser.newPage();
await page.goto('https://example.com');
const image = await page.screenshot();
expect(image).toMatchImageSnapshot({
failureThreshold: '0.10',
failureThresholdType: 'percent'
});
});
afterAll(async () => {
await browser.close();
});
});

If you are testing on localhost, you can easily configure jest to start the server before running the tests.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved