1- // utils/imageComparator.js
21const fs = require ( 'fs' ) ;
32const path = require ( 'path' ) ;
3+ const os = require ( 'os' ) ;
44const looksSame = require ( 'looks-same' ) ;
55
66function ensureDirSync ( dir ) {
7- if ( ! fs . existsSync ( dir ) ) {
7+ if ( ! fs . existsSync ( dir ) ) {
88 fs . mkdirSync ( dir , { recursive : true } ) ;
99 }
1010}
@@ -13,28 +13,33 @@ async function compareImages({ imageBuffer, snapshotPath, diffPath, threshold =
1313 ensureDirSync ( path . dirname ( snapshotPath ) ) ;
1414 ensureDirSync ( path . dirname ( diffPath ) ) ;
1515
16- // If no snapshot exists, create it
17- if ( ! fs . existsSync ( snapshotPath ) ) {
16+ // If no snapshot exists, save one and return
17+ if ( ! fs . existsSync ( snapshotPath ) ) {
1818 fs . writeFileSync ( snapshotPath , imageBuffer ) ;
1919 return { equal : true , created : true } ;
2020 }
2121
22+ // Write current image to temp file for diffing
23+ const tempPath = path . join ( os . tmpdir ( ) , `current-${ Date . now ( ) } .png` ) ;
24+ fs . writeFileSync ( tempPath , imageBuffer ) ;
25+
2226 return new Promise ( ( resolve , reject ) => {
23- looksSame ( imageBuffer , fs . readFileSync ( snapshotPath ) , {
24- tolerance : threshold ,
25- } , ( err , { equal } ) => {
26- if ( err ) return reject ( err ) ;
27+ looksSame ( tempPath , snapshotPath , { tolerance : threshold } , ( err , { equal } ) => {
28+ if ( err ) return reject ( err ) ;
2729
28- if ( ! equal ) {
30+ if ( ! equal ) {
2931 looksSame . createDiff ( {
3032 reference : snapshotPath ,
31- current : imageBuffer ,
33+ current : tempPath ,
3234 diff : diffPath ,
33- highlightColor : '#ff00ff' , // pink
34- } , ( ) => {
35- resolve ( { equal : false , created : false } ) ;
35+ highlightColor : '#ff00ff'
36+ } , ( diffErr ) => {
37+ fs . unlinkSync ( tempPath ) ; // Clean up temp file
38+ if ( diffErr ) return reject ( diffErr ) ;
39+ resolve ( { equal : false , created : false } ) ;
3640 } ) ;
3741 } else {
42+ fs . unlinkSync ( tempPath ) ;
3843 resolve ( { equal : true , created : false } ) ;
3944 }
4045 } ) ;
0 commit comments