Created
August 18, 2020 08:35
-
-
Save aulisius/f19a98243d8f93a05c44188ea39f8786 to your computer and use it in GitHub Desktop.
Cypress Blink Image Diff Plugin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require("fs-extra"); | |
const BlinkDiff = require("blink-diff"); | |
const path = require("path"); | |
module.exports = function diffImage(props) { | |
const imageName = path.basename(props.path); | |
if (imageName.endsWith("(failed).png")) { | |
return; | |
} | |
// There's already a folder 'screengrabs' created before Cypress runs | |
const snapshotPath = path.join("cypress", "screengrabs", imageName); | |
if (fs.pathExistsSync(snapshotPath)) { | |
// There's already a folder 'screendiff' created before Cypress runs | |
const diffPath = path.join("cypress", "screendiff", imageName); | |
const diff = new BlinkDiff({ | |
imageAPath: props.path, | |
imageBPath: snapshotPath, | |
thresholdType: BlinkDiff.THRESHOLD_PERCENT, | |
threshold: 0.0001, | |
imageOutputPath: diffPath | |
}); | |
return new Promise((resolve, reject) => { | |
diff.run((error, result) => { | |
fs.removeSync(props.path); | |
if (error) { | |
resolve( | |
"Failed to run blink-diff due to this error: ", | |
error.message | |
); | |
console.error(error); | |
} else { | |
const pixelDiff = (result.differences / result.dimension) * 100; | |
if (diff.hasPassed(result.code)) { | |
fs.removeSync(diffPath); | |
resolve("Screengrab didn't match by " + pixelDiff.toFixed(3)); | |
console.log("Screengrab didn't match by " + pixelDiff.toFixed(3)); | |
} else { | |
reject( | |
new Error( | |
"Screengrab didn't match by " + | |
pixelDiff.toFixed(3) + | |
"%. Check file " + | |
imageName | |
) | |
); | |
} | |
} | |
}); | |
}); | |
} else { | |
fs.moveSync(props.path, snapshotPath); | |
return Promise.resolve("Success"); | |
} | |
}; | |
// Usage in cypress/plugins/index.js | |
module.exports = (on, config) => { | |
// `on` is used to hook into various events Cypress emits | |
// `config` is the resolved Cypress config | |
on("after:screenshot", diffImage); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment