UNPKG

16.7 kBMarkdownView Raw
1<h1 align="center">
2 <img src='https://github.com/americanexpress/jest-image-snapshot/raw/main/images/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![Health Check](https://github.com/americanexpress/jest-image-snapshot/workflows/Health%20Check/badge.svg)
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
13Want 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
34Given 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
36On subsequent test runs the matcher will compare the image being passed against the stored snapshot.
37
38To 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
42Typically 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:
43
44```javascript
45...
46it('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="https://raw.githubusercontent.com/americanexpress/jest-image-snapshot/main/images/create-snapshot.gif" width="50%">
57
58Then 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="https://raw.githubusercontent.com/americanexpress/jest-image-snapshot/main/images/fail-snapshot.gif" width="50%">
61
62Oh 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="https://raw.githubusercontent.com/americanexpress/jest-image-snapshot/main/images/image-diff.png" width="50%">
65
66And now that I know that I broke the card art I can fix it!
67
68Thanks `jest-image-snapshot`, that broken header would not have looked good in production!
69
70## ๐Ÿคนโ€ Usage
71
72### Installation
73
74```bash
75npm i --save-dev jest-image-snapshot
76```
77
78Please note that `Jest` `>=20 <=27` is a peerDependency. `jest-image-snapshot` will **not** work with anything below Jest 20.x.x
79
80### Invocation
81
821. Extend Jest's `expect`
83```javascript
84 const { toMatchImageSnapshot } = require('jest-image-snapshot');
85
86 expect.extend({ toMatchImageSnapshot });
87```
88
892. Use `toMatchImageSnapshot()` in your tests!
90```javascript
91 it('should demonstrate this matcher`s usage', () => {
92 ...
93 expect(image).toMatchImageSnapshot();
94 });
95```
96
97See [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) or [ssim.js](https://github.com/obartra/ssim/wiki/Usage#options)
104 * Pixelmatch specific options
105 * By default we have set the `threshold` to 0.01, you can increase that value by passing a customDiffConfig as demonstrated below.
106 * 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)
107 * SSIM specific options
108 * By default we set `ssim` to 'bezkrovny'. It is the fastest option and best option most of the time. In cases where, higher precision is needed, this can be set to 'fast'. See [SSIM Performance Consideration](#ssim-performance-considerations) for a better understanding of how to use this feature.
109* `comparisonMethod`: (default: `pixelmatch`) (options `pixelmatch` or `ssim`) The method by which images are compared. `pixelmatch` does a pixel by pixel comparison, whereas `ssim` does a structural similarity comparison. `ssim` is a new experimental feature for jest-image-snapshot, but may become the default comparison method in the future. For a better understanding of how to use SSIM, see [Recommendations when using SSIM Comparison](#recommendations-when-using-ssim-comparison).
110* `customSnapshotsDir`: A custom absolute path of a directory to keep this snapshot in
111* `customDiffDir`: A custom absolute path of a directory to keep this diff in
112* `storeReceivedOnFailure`: (default: `false`) Store the received images seperately from the composed diff images on failure. This can be useful when updating baseline images from CI.
113* `customReceivedDir`: A custom absolute path of a directory to keep this received image in
114* `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. If a path is given, the path will be created inside the snapshot/diff directories.
115* `diffDirection`: (default: `horizontal`) (options `horizontal` or `vertical`) Changes diff image layout direction
116* `noColors`: Removes coloring from console output, useful if storing the results in a file
117* `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.
118* `failureThresholdType`: (default `pixel`) (options `percent` or `pixel`) Sets the type of threshold that would trigger a failure.
119* `updatePassedSnapshot`: (default `false`) Updates a snapshot even if it passed the threshold against the existing one.
120* `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.
121* `runInProcess`: (default `false`) Runs the diff in process without spawning a child process.
122* `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.
123* `dumpInlineDiffToConsole`: (default `false`) Will output the image to the terminal using iTerm's [Inline Images Protocol](https://iterm2.com/documentation-images.html). If the term is not compatible, it does the same thing as `dumpDiffToConsole`.
124* `allowSizeMismatch`: (default `false`) If set to true, the build will not fail when the screenshots to compare have different sizes.
125
126```javascript
127it('should demonstrate this matcher`s usage with a custom pixelmatch config', () => {
128 ...
129 const customConfig = { threshold: 0.5 };
130 expect(image).toMatchImageSnapshot({
131 customDiffConfig: customConfig,
132 customSnapshotIdentifier: 'customSnapshotName',
133 noColors: true
134 });
135});
136```
137
138The failure threshold can be set in percent, in this case if the difference is over 1%.
139
140```javascript
141it('should fail if there is more than a 1% difference', () => {
142 ...
143 expect(image).toMatchImageSnapshot({
144 failureThreshold: 0.01,
145 failureThresholdType: 'percent'
146 });
147});
148```
149
150Custom 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:
151
152```javascript
153const { configureToMatchImageSnapshot } = require('jest-image-snapshot');
154
155const customConfig = { threshold: 0 };
156const toMatchImageSnapshot = configureToMatchImageSnapshot({
157 customDiffConfig: customConfig,
158 noColors: true,
159});
160expect.extend({ toMatchImageSnapshot });
161```
162
163### jest.retryTimes()
164Jest 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.
165
166### Removing Outdated Snapshots
167
168Unlike 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`.
169
170```json
171{
172 "jest": {
173 "reporters": [
174 "default",
175 "jest-image-snapshot/src/outdated-snapshot-reporter.js"
176 ]
177 }
178}
179```
180
181**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.**
182
183```bash
184export JEST_IMAGE_SNAPSHOT_TRACK_OBSOLETE=1
185jest
186```
187
188### Recommendations when using SSIM comparison
189Since 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:
190- Reduced false positives (failing tests when the images look the same)
191- Higher sensitivity to actual changes in the image itself.
192
193Documentation 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"](https://ece.uwaterloo.ca/~z70wang/publications/MAD.pdf) 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](https://en.wikipedia.org/wiki/Structural_similarity) also provides many great reference sources describing the topic.
194
195As 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.
196
197```javascript
198it('should fail if there is more than a 1% difference (ssim)', () => {
199 ...
200 expect(image).toMatchImageSnapshot({
201 comparisonMethod: 'ssim',
202 failureThreshold: 0.01,
203 failureThresholdType: 'percent'
204 });
205});
206```
207### SSIM Performance Considerations
208The default SSIM comparison method used in the jest-image-snapshot implementation is 'bezkrovny' (as a `customDiffConfig` `{ssim: 'bezkrovny'}`).
209Bezkrovny 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.
210This 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,
211this 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.
212
213The following is an example configuration for using `{ssim: 'fast'}` with toMatchImageSnapshot().
214```javascript.
215{
216 comparisonMethod: 'ssim',
217 customDiffConfig: {
218 ssim: 'fast',
219 },
220 failureThreshold: 0.01,
221 failureThresholdType: 'percent'
222}
223```
224
225
226### Recipes
227
228#### Upload diff images from failed tests
229
230[Example Image Upload Test Reporter](examples/image-reporter.js)
231
232If 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.
233
234To enable this image reporter, add it to your `jest.config.js` "reporters" definition:
235
236```javascript
237"reporters": [ "default", "<rootDir>/image-reporter.js" ]
238```
239
240#### Usage in TypeScript
241
242In TypeScript, you can use the [DefinitelyTyped](https://www.npmjs.com/package/@types/jest-image-snapshot) definition or declare `toMatchImageSnapshot` like the example below:
243
244_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._
245
246
247```typescript
248declare global {
249 namespace jest {
250 interface Matchers<R> {
251 toMatchImageSnapshot(): R
252 }
253 }
254}
255```
256
257#### Ignoring parts of the image snapshot if using [Puppeteer](https://github.com/GoogleChrome/puppeteer)
258
259If 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):
260
261```javascript
262async function removeBanners(page){
263 await page.evaluate(() => {
264 (document.querySelectorAll('.banner') || []).forEach(el => el.remove());
265 });
266}
267
268...
269it('renders correctly', async () => {
270 const page = await browser.newPage();
271 await page.goto('https://localhost:3000');
272
273 await removeBanners(page);
274
275 const image = await page.screenshot();
276
277 expect(image).toMatchImageSnapshot();
278});
279...
280```
281
282## ๐Ÿ† Contributing
283
284We welcome Your interest in the American Express Open Source Community on Github.
285Any Contributor to any Open Source Project managed by the American Express Open
286Source Community must accept and sign an Agreement indicating agreement to the
287terms below. Except for the rights granted in this Agreement to American Express
288and to recipients of software distributed by American Express, You reserve all
289right, title, and interest, if any, in and to Your Contributions. Please [fill
290out the Agreement](https://cla-assistant.io/americanexpress/jest-image-snapshot).
291
292Please feel free to open pull requests and see [CONTRIBUTING.md](./CONTRIBUTING.md) to learn how to get started contributing.
293
294## ๐Ÿ—๏ธ License
295
296Any contributions made under this project will be governed by the [Apache License
2972.0](https://github.com/americanexpress/jest-image-snapshot/blob/main/LICENSE.txt).
298
299## ๐Ÿ—ฃ๏ธ Code of Conduct
300
301This project adheres to the [American Express Community Guidelines](https://github.com/americanexpress/jest-image-snapshot/wiki/Code-of-Conduct).
302By participating, you are expected to honor these guidelines.