1 | <h1 align="center">
|
2 | <img src='https://github.com/americanexpress/jest-image-snapshot/raw/master/jest-image-snapshot.png' alt="Jest Image Snapshot - One Amex" width='50%'/>
|
3 | </h1>
|
4 |
|
5 | [![npm](https://img.shields.io/npm/v/jest-image-snapshot)](https://www.npmjs.com/package/jest-image-snapshot)
|
6 | [![Travis (.org) branch](https://img.shields.io/travis/americanexpress/jest-image-snapshot/master)](https://travis-ci.org/americanexpress/jest-image-snapshot)
|
7 | [![Mentioned in Awesome Jest](https://awesome.re/mentioned-badge.svg)](https://github.com/jest-community/awesome-jest)
|
8 |
|
9 | > Jest matcher that performs image comparisons using [pixelmatch](https://github.com/mapbox/pixelmatch) and behaves just like [Jest snapshots](https://facebook.github.io/jest/docs/snapshot-testing.html) do! Very useful for visual regression testing.
|
10 |
|
11 | ## ๐ฉโ๐ป Hiring ๐จโ๐ป
|
12 |
|
13 | Want to get paid for your contributions to `jest-image-snapshot`?
|
14 | > Send your resume to oneamex.careers@aexp.com
|
15 |
|
16 | ## ๐ Table of Contents
|
17 |
|
18 | * [Features](#-features)
|
19 | * [Usage](#-usage)
|
20 | * [API](#-api)
|
21 | * [Contributing](#-contributing)
|
22 |
|
23 | ## โจ Features
|
24 |
|
25 | * Take image snapshots of your application
|
26 | * Ability to compare snapshots from a baseline
|
27 | * Update snapshots when you're good with changes
|
28 | * Customize a difference threshold
|
29 | * Add a Gaussian blur for noise
|
30 | * Adjust the diff layout horizontal vs vertical
|
31 |
|
32 | ### How it works
|
33 |
|
34 | 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.
|
35 |
|
36 | On subsequent test runs the matcher will compare the image being passed against the stored snapshot.
|
37 |
|
38 | To update the stored image snapshot run Jest with `--updateSnapshot` or `-u` argument. All this works the same way as [Jest snapshots](https://facebook.github.io/jest/docs/snapshot-testing.html).
|
39 |
|
40 | ### See it in action
|
41 |
|
42 | Typically this matcher is used to 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:
|
43 |
|
44 | ```javascript
|
45 | ...
|
46 | it('renders correctly', async () => {
|
47 | const page = await browser.newPage();
|
48 | await page.goto('https://localhost:3000');
|
49 | const image = await page.screenshot();
|
50 |
|
51 | expect(image).toMatchImageSnapshot();
|
52 | });
|
53 | ...
|
54 | ```
|
55 |
|
56 | <img title="Adding an image snapshot" src="./images/create-snapshot.gif" width="50%">
|
57 |
|
58 | Then after a few days as I finish adding another feature to my component I notice one of my tests failing!
|
59 |
|
60 | <img title="A failing image snapshot test" src="./images/fail-snapshot.gif" width="50%">
|
61 |
|
62 | Oh no! I must have introduced a regression! Let's see what the diff looks like to identify what I need to fix:
|
63 |
|
64 | <img title="Image diff" src="./images/image-diff.png" width="50%">
|
65 |
|
66 | And now that I know that I broke the card art I can fix it!
|
67 |
|
68 | Thanks `jest-image-snapshot`, that broken header would not have looked good in production!
|
69 |
|
70 | ## ๐คนโ Usage
|
71 |
|
72 | ### Installation
|
73 |
|
74 | ```bash
|
75 | npm i --save-dev jest-image-snapshot
|
76 | ```
|
77 |
|
78 | Please note that `Jest` `>=20 <=25` is a peerDependency. `jest-image-snapshot` will **not** work with anything below Jest 20.x.x
|
79 |
|
80 | ### Invocation
|
81 |
|
82 | 1. Extend Jest's `expect`
|
83 | ```javascript
|
84 | const { toMatchImageSnapshot } = require('jest-image-snapshot');
|
85 |
|
86 | expect.extend({ toMatchImageSnapshot });
|
87 | ```
|
88 |
|
89 | 2. Use `toMatchImageSnapshot()` in your tests!
|
90 | ```javascript
|
91 | it('should demonstrate this matcher`s usage', () => {
|
92 | ...
|
93 | expect(image).toMatchImageSnapshot();
|
94 | });
|
95 | ```
|
96 |
|
97 | See [the examples](./examples/README.md) for more detailed usage or read about an example use case in the [American Express Technology Blog](https://americanexpress.io/smile-for-the-camera/)
|
98 |
|
99 | ## ๐๏ธ API
|
100 |
|
101 | `toMatchImageSnapshot()` takes an optional options object with the following properties:
|
102 |
|
103 | * `customDiffConfig`: Custom config passed to [pixelmatch](https://github.com/mapbox/pixelmatch#pixelmatchimg1-img2-output-width-height-options) (See options section)
|
104 | * By default we have set the `threshold` to 0.01, you can increase that value by passing a customDiffConfig as demonstrated below.
|
105 | * Please note the `threshold` set in the `customDiffConfig` is the per pixel sensitivity threshold. For example with a source pixel colour of `#ffffff` (white) and a comparison pixel colour of `#fcfcfc` (really light grey) if you set the threshold to 0 then it would trigger a failure *on that pixel*. However if you were to use say 0.5 then it wouldn't, the colour difference would need to be much more extreme to trigger a failure on that pixel, say `#000000` (black)
|
106 | * `customSnapshotsDir`: A custom absolute path of a directory to keep this snapshot in
|
107 | * `customDiffDir`: A custom absolute path of a directory to keep this diff in
|
108 | * `customSnapshotIdentifier`: A custom name to give this snapshot. If not provided one is computed automatically. When a function is provided it is called with an object containing `testPath`, `currentTestName`, `counter` and `defaultIdentifier` as its first argument. The function must return an identifier to use for the snapshot.
|
109 | * `diffDirection`: (default: `horizontal`) (options `horizontal` or `vertical`) Changes diff image layout direction
|
110 | * `noColors`: Removes coloring from console output, useful if storing the results in a file
|
111 | * `failureThreshold`: (default `0`) Sets the threshold that would trigger a test failure based on the `failureThresholdType` selected. This is different to the `customDiffConfig.threshold` above, that is the per pixel failure threshold, this is the failure threshold for the entire comparison.
|
112 | * `failureThresholdType`: (default `pixel`) (options `percent` or `pixel`) Sets the type of threshold that would trigger a failure.
|
113 | * `updatePassedSnapshot`: (default `false`) Updates a snapshot even if it passed the threshold against the existing one.
|
114 | * `blur`: (default `0`) Applies Gaussian Blur on compared images, accepts radius in pixels as value. Useful when you have noise after scaling images per different resolutions on your target website, usually setting its value to 1-2 should be enough to solve that problem.
|
115 | * `runInProcess`: (default `false`) Runs the diff in process without spawning a child process.
|
116 | * `dumpDiffToConsole`: (default `false`) Will output base64 string of a diff image to console in case of failed tests (in addition to creating a diff image). This string can be copy-pasted to a browser address string to preview the diff for a failed test.
|
117 | * `allowSizeMismatch`: (default `false`) If set to true, the build will not fail when the screenshots to compare have different sizes.
|
118 |
|
119 | ```javascript
|
120 | it('should demonstrate this matcher`s usage with a custom pixelmatch config', () => {
|
121 | ...
|
122 | const customConfig = { threshold: 0.5 };
|
123 | expect(image).toMatchImageSnapshot({
|
124 | customDiffConfig: customConfig,
|
125 | customSnapshotIdentifier: 'customSnapshotName',
|
126 | noColors: true
|
127 | });
|
128 | });
|
129 | ```
|
130 |
|
131 | The failure threshold can be set in percent, in this case if the difference is over 1%.
|
132 |
|
133 | ```javascript
|
134 | it('should fail if there is more than a 1% difference', () => {
|
135 | ...
|
136 | expect(image).toMatchImageSnapshot({
|
137 | failureThreshold: 0.01,
|
138 | failureThresholdType: 'percent'
|
139 | });
|
140 | });
|
141 | ```
|
142 |
|
143 | 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:
|
144 |
|
145 | ```javascript
|
146 | const { configureToMatchImageSnapshot } = require('jest-image-snapshot');
|
147 |
|
148 | const customConfig = { threshold: 0 };
|
149 | const toMatchImageSnapshot = configureToMatchImageSnapshot({
|
150 | customDiffConfig: customConfig,
|
151 | noColors: true,
|
152 | });
|
153 | expect.extend({ toMatchImageSnapshot });
|
154 | ```
|
155 |
|
156 | ### jest.retryTimes()
|
157 | Jest supports [automatic retries on test failures](https://jestjs.io/docs/en/jest-object#jestretrytimes). 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.
|
158 |
|
159 | ### Recipes
|
160 |
|
161 | #### Upload diff images from failed tests
|
162 |
|
163 | [Example Image Upload Test Reporter](examples/image-reporter.js)
|
164 |
|
165 | 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](https://facebook.github.io/jest/docs/en/configuration.html#reporters-array-modulename-modulename-options) 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](https://aws.amazon.com/s3/) bucket.
|
166 |
|
167 | To enable this image reporter, add it to your `jest.config.js` "reporters" definition:
|
168 |
|
169 | ```javascript
|
170 | "reporters": [ "default", "<rootDir>/image-reporter.js" ]
|
171 | ```
|
172 |
|
173 | #### Usage in TypeScript
|
174 |
|
175 | In TypeScript, you can declare `toMatchImageSnapshot` like this:
|
176 |
|
177 | ```
|
178 | declare global {
|
179 | namespace jest {
|
180 | interface Matchers<R> {
|
181 | toMatchImageSnapshot(): R
|
182 | }
|
183 | }
|
184 | }
|
185 | ```
|
186 |
|
187 | #### Ignoring parts of the image snapshot if using [Puppeteer](https://github.com/GoogleChrome/puppeteer)
|
188 |
|
189 | If you want to 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):
|
190 |
|
191 | ```javascript
|
192 | async function removeBanners(page){
|
193 | await page.evaluate(() => {
|
194 | (document.querySelectorAll('.banner') || []).forEach(el => el.remove());
|
195 | });
|
196 | }
|
197 |
|
198 | ...
|
199 | it('renders correctly', async () => {
|
200 | const page = await browser.newPage();
|
201 | await page.goto('https://localhost:3000');
|
202 |
|
203 | await removeBanners(page);
|
204 |
|
205 | const image = await page.screenshot();
|
206 |
|
207 | expect(image).toMatchImageSnapshot();
|
208 | });
|
209 | ...
|
210 | ```
|
211 |
|
212 | ## ๐ Contributing
|
213 |
|
214 | We welcome Your interest in the American Express Open Source Community on Github.
|
215 | Any Contributor to any Open Source Project managed by the American Express Open
|
216 | Source Community must accept and sign an Agreement indicating agreement to the
|
217 | terms below. Except for the rights granted in this Agreement to American Express
|
218 | and to recipients of software distributed by American Express, You reserve all
|
219 | right, title, and interest, if any, in and to Your Contributions. Please [fill
|
220 | out the Agreement](https://cla-assistant.io/americanexpress/jest-image-snapshot).
|
221 |
|
222 | Please feel free to open pull requests and see [CONTRIBUTING.md](./CONTRIBUTING.md) to learn how to get started contributing.
|
223 |
|
224 | ## ๐๏ธ License
|
225 |
|
226 | Any contributions made under this project will be governed by the [Apache License
|
227 | 2.0](https://github.com/americanexpress/jest-image-snapshot/blob/master/LICENSE.txt).
|
228 |
|
229 | ## ๐ฃ๏ธ Code of Conduct
|
230 |
|
231 | This project adheres to the [American Express Community Guidelines](https://github.com/americanexpress/jest-image-snapshot/wiki/Code-of-Conduct).
|
232 | By participating, you are expected to honor these guidelines.
|