Skip to content

A jest extension to deal with screenshots and all sorts of images.

License

Notifications You must be signed in to change notification settings

Prior99/jest-screenshot

Repository files navigation

jest-screenshot

npm Build Status Coverage Status

A jest extension to deal with screenshots and all sorts of images. Inspired by the awesome jest-image-snapshot and providing a mostly compatible API with similar features. By utilizing native-image-diff instead of pixelmatch and node-libpng instead of pngjs the tests will run much faster than its competitor.

Please also refer to the Documentation.

Table of contents

Installation

Two steps are necessary in order to use this plugin:

  1. Install the expect().toMatchImageSnapshot() extension. (Here)
  2. Install the reporter. (Here)

Installing the expect extension

Integrate this plugin by calling setupJestScreenshot in the framework setup file:

import { setupJestScreenshot } from "jest-screenshot";

setupJestScreenshot();

Store the above code in a setup-framework.js file and specify it when configuring Jest:

"jest": {

    "setupTestFrameworkScriptFile": "<rootDir>/setup-framework.js"

}

TypeScript Tip: to enable jest matcher types for toMatchImageSnapshot(), use a *.ts for your setup file.

Installing the reporter

In order to generate the report, the reporter must be registered in the Jest configuration:

"jest": {

    "reporters": [
        "default",
        "jest-screenshot/reporter"
    ]

}

Configuring

By placing a file jest-screenshot.json in the root directory of your project with a configuration object you can configure it:

Parameter type default Description
detectAntialiasing boolean true Whether to attempt to detect antialiasing and ignore related changes when comparing both images. See documentation.
colorThreshold number 0.1 A number in the range from 0 to 1 describing how sensitive the comparison of two pixels should be. See documentation.
pixelThresholdAbsolute number undefined If specified, jest-screenshot will fail if more than the specified pixels are different from the snapshot.
pixelThresholdRelative number 0 If specified, jest-screenshot will fail if more than the specified relative amount of pixels are different from the snapshot. When setting this to 0.5 for example, more than 50% of the pixels need to be different for the test to fail.
snapshotsDir string __snapshots__ If specified, will change the directory into which the snapshot images will be stored, relative to the unit test file.
reportDir string jest-screenshot-report If specified, will change the directory into which the HTML report will be written, relative to the project's root directory.
noReport boolean false Set this to true in order to completely disable the HTML report.

It's also possible to specify a key jestScreenshot in the package.json with the same interface.

All configuration options are optional.

If neither pixelThresholdAbsolute nor pixelThresholdRelative are specified, pixelThresholdRelative will be set to 0. Both can be specified together in order to make the test fail on both conditions.

Example

{
    "detectAntialiasing": false,
    "colorThreshold": 0,
    "pixelThresholdAbsolute": 150,
    "pixelThresholdRelative": 0.5
};

The above config will make the tests fail if more than 150 pixels in total changed or more than 50% of the pixels changed. It will detect any pixel as changed even if the color only differs minimally and antialiasing detection is disabled.

Usage

Take a look at the example project.

This library can be used to compare images with snapshots:

describe("My fancy image", () => {
    const myFancyImage = readFileSync("../my-fancy-image.png");

    it("looks as beautiful as always", () => {
        expect(myFancyImage).toMatchImageSnapshot();
    });
});

This is for example useful for integration tests with puppeteer:

describe("My fancy webpage", () => {
    const page = ...; // Setup puppeteer.

    it("looks as gorgeous as ever", async () => {
        expect(await page.screenshot()).toMatchImageSnapshot();
    });
});

It is possible to specify a custom path to store the snapshot at:

describe("My fancy image", () => {
    const myFancyImage = readFileSync("../my-fancy-image.png");

    it("looks as beautiful as always", () => {
        expect(myFancyImage).toMatchImageSnapshot({ path: "../../my-fancy-image.snap.png" });
    });
});

It is possible to import toMatchImageSnapshot() for custom assertions. As it requires configuration as second argument, config() function (which is responsible for reading configuration from jest-screenshot.json/package.json) is also exposed.

import {config, toMatchImageSnapshot} from 'jest-screenshot';

expect.extend({
  customMatcher(received, name) {
    const image = customGetImage(received); // i.e. via puppeteer, html2canvas etc
    const configuration = config(); // get existing config
    if(process.env.LOOSE_SCREENSHOTS_MATCH) {
        // loose mismatch threshold for specific environment setting
        configuration.pixelThresholdRelative = configuration.pixelThresholdRelative + 0.1
    }
    return toMatchImageSnapshot.call(this, image, configuration, {
        // build custom path for screenshot
        path: `/custom_file_path/${configuration.snapshotsDir}/custom_file_prefix_${name}.png`
    });
  }
});

Benchmark

This library is around 10x faster than jest-image-snapshot.

In the benchmark a whole unit test suite, including setup and teardown of the jest environment and 30 unit tests (10 matching, 10 not matching and 10 newly created) were measured. Writing of the report is also included.

Benchmark

The X axis displays the amount of executed suites per second.

In average:

  • jest-screenshot took ~9 seconds for 30 tests and
  • jest-image-snapshot took >100 seconds.

Reports

An HTML report with interactive tools for comparing the failed snapshots will be generated if any tests failed.

A demo can be found here.

They might look for example like this:

Example Report

The report will be placed in a jest-screenshot-report directory in the project's root directory by default.

Contributing

Yarn is used instead of npm, so make sure it is installed. npm install -g yarn.

Generally, it should be enough to just run:

make

which will install all node dependencies, compile typescript, execute all test, lint the sources and build the docs.

Contributors

  • Frederick Gnodtke

About

A jest extension to deal with screenshots and all sorts of images.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •