americanexpress / jest-image-snapshot

โœจ Jest matcher for image comparisons. Most commonly used for visual regression testing.
Apache License 2.0
3.81k stars 197 forks source link
image-comparisons image-snapshots jest jest-snapshots one-app snapshot testing visual-comparison-testing

Jest Image Snapshot - One Amex

npm Health Check Mentioned in Awesome Jest

Jest matcher that performs image comparisons using pixelmatch and behaves just like Jest snapshots do! Very useful for visual regression testing.

๐Ÿ‘ฉโ€๐Ÿ’ป Hiring ๐Ÿ‘จโ€๐Ÿ’ป

Want to get paid for your contributions to jest-image-snapshot?

Send your resume to oneamex.careers@aexp.com

๐Ÿ“– Table of Contents

โœจ Features

How it works

Given an image (Buffer instance with PNG image data) the toMatchImageSnapshot() matcher will create a __image_snapshots__ directory in the directory the test is in and will store the baseline snapshot image there on the first run. Note that if customSnapshotsDir option is given then it will store baseline snapshot there instead.

On subsequent test runs the matcher will compare the image being passed against the stored snapshot.

To update the stored image snapshot run Jest with --updateSnapshot or -u argument. All this works the same way as Jest snapshots.

See it in action

Typically this matcher is used for visual tests that run on a browser. For example let's say I finish working on a feature and want to write a test to prevent visual regressions:

...
it('renders correctly', async () => {
  const page = await browser.newPage();
  await page.goto('https://localhost:3000');
  const image = await page.screenshot();

  expect(image).toMatchImageSnapshot();
});
...

Then after a few days as I finish adding another feature to my component I notice one of my tests failing!

Oh no! I must have introduced a regression! Let's see what the diff looks like to identify what I need to fix:

And now that I know that I broke the card art I can fix it!

Thanks jest-image-snapshot, that broken header would not have looked good in production!

๐Ÿคนโ€ Usage

Installation

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

Please note that Jest >=20 <=29 is a peerDependency. jest-image-snapshot will not work with anything below Jest 20.x.x

Invocation

  1. Extend Jest's expect

    const { toMatchImageSnapshot } = require('jest-image-snapshot');
    
    expect.extend({ toMatchImageSnapshot });
  2. Use toMatchImageSnapshot() in your tests!

    it('should demonstrate this matcher`s usage', () => {
    ...
    expect(image).toMatchImageSnapshot();
    });

See the examples for more detailed usage or read about an example use case in the American Express Technology Blog

๐ŸŽ›๏ธ API

toMatchImageSnapshot() takes an optional options object with the following properties:

it('should demonstrate this matcher`s usage with a custom pixelmatch config', () => {
  ...
  const customConfig = { threshold: 0.5 };
  expect(image).toMatchImageSnapshot({
    customDiffConfig: customConfig,
    customSnapshotIdentifier: 'customSnapshotName',
    noColors: true
  });
});

The failure threshold can be set in percent, in this case if the difference is over 1%.

it('should fail if there is more than a 1% difference', () => {
  ...
  expect(image).toMatchImageSnapshot({
    failureThreshold: 0.01,
    failureThresholdType: 'percent'
  });
});

Custom defaults can be set with a configurable extension. This will allow for customization of this module's defaults. For example, a 0% default threshold can be shared across all tests with the configuration below:

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

const customConfig = { threshold: 0 };
const toMatchImageSnapshot = configureToMatchImageSnapshot({
  customDiffConfig: customConfig,
  noColors: true,
});
expect.extend({ toMatchImageSnapshot });

jest.retryTimes()

Jest supports automatic retries on test failures. This can be useful for browser screenshot tests which tend to have more frequent false positives. Note that when using jest.retryTimes you'll have to use a unique customSnapshotIdentifier as that's the only way to reliably identify snapshots.

Removing Outdated Snapshots

Unlike jest-managed snapshots, the images created by jest-image-snapshot will not be automatically removed by the -u flag if they are no longer needed. You can force jest-image-snapshot to remove the files by including the outdated-snapshot-reporter in your config and running with the environment variable JEST_IMAGE_SNAPSHOT_TRACK_OBSOLETE.

{
  "jest": {
    "reporters": [
      "default",
      "jest-image-snapshot/src/outdated-snapshot-reporter.js"
    ]
  }
}

WARNING: Do not run a partial test suite with this flag as it may consider snapshots of tests that weren't run to be obsolete.

export JEST_IMAGE_SNAPSHOT_TRACK_OBSOLETE=1
jest

Recommendations when using SSIM comparison

Since SSIM calculates differences in structural similarity by building a moving 'window' over an images pixels, it does not particularly benefit from pixel count comparisons, especially when you factor in that it has a lot of floating point arithmetic in javascript. However, SSIM gains two key benefits over pixel by pixel comparison:

Documentation supporting these claims can be found in the many analyses comparing SSIM to Peak Signal to Noise Ratio (PSNR). See Wang, Z.; Simoncelli, E. P. (September 2008). "Maximum differentiation (MAD) competition: a methodology for comparing computational models of perceptual quantities" and Zhang, L.; Zhang, L.; Mou, X.; Zhang, D. (September 2012). A comprehensive evaluation of full reference image quality assessment algorithms. 2012 19th IEEE International Conference on Image Processing. pp. 1477โ€“1480. Wikipedia also provides many great reference sources describing the topic.

As such, most users can benefit from setting a 1% or 0.01 threshold for any SSIM comparison. The below code shows a one line modification of the 1% threshold example.

it('should fail if there is more than a 1% difference (ssim)', () => {
  ...
  expect(image).toMatchImageSnapshot({
    comparisonMethod: 'ssim',
    failureThreshold: 0.01,
    failureThresholdType: 'percent'
  });
});

SSIM Performance Considerations

The default SSIM comparison method used in the jest-image-snapshot implementation is 'bezkrovny' (as a customDiffConfig {ssim: 'bezkrovny'}). Bezkrovny is a special implementation of SSIM that is optimized for speed at a small, almost inconsequential change in accuracy. It gains this benefit by downsampling (or shrinking the original image) before performing the comparisons. This will provide the best combination of results and performance most of the time. When the need arises where higher accuracy is desired at the expense of time or a higher quality diff image is needed for debugging, this option can be changed to {ssim: 'fast'}. This uses the original SSIM algorithm described in Wang, et al. 2004 on "Image Quality Assessment: From Error Visibility to Structural Similarity" (https://github.com/obartra/ssim/blob/master/assets/ssim.pdf) optimized for javascript.

The following is an example configuration for using {ssim: 'fast'} with toMatchImageSnapshot().

{
  comparisonMethod: 'ssim',
  customDiffConfig: {
    ssim: 'fast',
  },
  failureThreshold: 0.01,
  failureThresholdType: 'percent'
}

Recipes

Upload diff images from failed tests

Example Image Upload Test Reporter

If you are using jest-image-snapshot in an ephemeral environment (like a Continuous Integration server) where the file system does not persist, you might want a way to retrieve those images for diagnostics or historical reference. This example shows how to use a custom Jest Reporter that will run after every test, and if there were any images created because they failed the diff test, upload those images to an AWS S3 bucket.

To enable this image reporter, add it to your jest.config.js "reporters" definition:

"reporters": [ "default", "<rootDir>/image-reporter.js" ]

Usage in TypeScript

In TypeScript, you can use the DefinitelyTyped definition or declare toMatchImageSnapshot like the example below:

Note: This package is not maintained by the jest-image-snapshot maintainers so it may be out of date or inaccurate. Because of this, we do not officially support it.

declare global {
  namespace jest {
    interface Matchers<R> {
      toMatchImageSnapshot(): R
    }
  }
}

Ignoring parts of the image snapshot if using Puppeteer

If you want to ignore parts of the snapshot (for example some banners or other dynamic blocks) you can find DOM elements with Puppeteer and remove/modify them (setting visibility: hidden on block, if removing it breaks your layout, should help):

async function removeBanners(page){
  await page.evaluate(() => {
    (document.querySelectorAll('.banner') || []).forEach(el => el.remove());
  });
}

...
it('renders correctly', async () => {
  const page = await browser.newPage();
  await page.goto('https://localhost:3000');

  await removeBanners(page);

  const image = await page.screenshot();

  expect(image).toMatchImageSnapshot();
});
...

๐Ÿ† Contributing

We welcome Your interest in the American Express Open Source Community on Github. Any Contributor to any Open Source Project managed by the American Express Open Source Community must accept and sign an Agreement indicating agreement to the terms below. Except for the rights granted in this Agreement to American Express and to recipients of software distributed by American Express, You reserve all right, title, and interest, if any, in and to Your Contributions. Please fill out the Agreement.

Please feel free to open pull requests and see CONTRIBUTING.md to learn how to get started contributing.

๐Ÿ—๏ธ License

Any contributions made under this project will be governed by the Apache License 2.0.

๐Ÿ—ฃ๏ธ Code of Conduct

This project adheres to the American Express Community Guidelines. By participating, you are expected to honor these guidelines.