1
1
import { readFileSync } from 'fs' ;
2
- function bitmapDiff ( imagePath , expectedImagePath ) {
3
- const PNG = require ( 'pngjs' ) . PNG ;
4
- const pixelmatch = require ( 'pixelmatch' ) ;
5
- const img1 = PNG . sync . read ( readFileSync ( imagePath ) ) ;
6
- const img2 = PNG . sync . read ( readFileSync ( expectedImagePath ) ) ;
7
- const { width, height } = img1 ;
8
- const diff = new PNG ( { width, height } ) ;
9
-
10
- return pixelmatch ( img1 . data , img2 . data , diff . data , width , height , { threshold : 0.01 } ) ;
2
+ import { PNG } from 'pngjs' ;
3
+ import { ssim } from 'ssim.js' ;
4
+
5
+ const SSIM_SCORE_THRESHOLD = 0.997 ;
6
+
7
+ function convertToSSIMFormat ( image ) {
8
+ return {
9
+ data : new Uint8ClampedArray ( image . data ) ,
10
+ width : image . width ,
11
+ height : image . height
12
+ }
13
+ ;
14
+ }
15
+
16
+ function loadImage ( path ) {
17
+ const image = PNG . sync . read ( readFileSync ( path ) ) ;
18
+
19
+ return convertToSSIMFormat ( image ) ;
20
+ }
21
+
22
+ function bitmapDiff ( imagePath , expectedImagePath , ssimThreshold = SSIM_SCORE_THRESHOLD ) {
23
+ const image = loadImage ( imagePath ) ;
24
+ const expectedImage = loadImage ( expectedImagePath ) ;
25
+
26
+ const { mssim, performance } = ssim ( image , expectedImage ) ;
27
+
28
+ if ( mssim < ssimThreshold ) {
29
+ throw new Error (
30
+ `Expected bitmaps at '${ imagePath } ' and '${ expectedImagePath } ' to have an SSIM score ` +
31
+ `of at least ${ SSIM_SCORE_THRESHOLD } , but got ${ mssim } . This means the snapshots are different ` +
32
+ `(comparison took ${ performance } ms)` ,
33
+ ) ;
34
+ }
11
35
}
36
+
12
37
const utils = {
13
38
elementByLabel : ( label ) => {
14
39
// uncomment for running tests with rn's new arch
@@ -35,15 +60,21 @@ const utils = {
35
60
} ,
36
61
sleep : ( ms ) => new Promise ( ( res ) => setTimeout ( res , ms ) ) ,
37
62
expectImagesToBeEqual : ( imagePath , expectedImagePath ) => {
38
- let diff = bitmapDiff ( imagePath , expectedImagePath ) ;
39
- if ( diff > 7000 ) {
40
- throw Error ( `${ imagePath } should be the same as ${ expectedImagePath } , with diff: ${ diff } ` ) ;
41
- }
63
+ bitmapDiff ( imagePath , expectedImagePath ) ;
64
+
42
65
} ,
43
66
expectImagesToBeNotEqual : ( imagePath , expectedImagePath ) => {
44
- let diff = bitmapDiff ( imagePath , expectedImagePath ) ;
45
- if ( diff === 0 ) {
46
- throw Error ( `${ imagePath } should be the same as ${ expectedImagePath } , with diff: ${ diff } ` ) ;
67
+ let isDifferent = false ;
68
+ try {
69
+ bitmapDiff ( imagePath , expectedImagePath ) ;
70
+ } catch ( error ) {
71
+ isDifferent = true ;
72
+ }
73
+
74
+ if ( ! isDifferent ) {
75
+ throw new Error (
76
+ `Expected bitmaps at '${ imagePath } ' and '${ expectedImagePath } ' to be different` ,
77
+ ) ;
47
78
}
48
79
} ,
49
80
} ;
0 commit comments