|
| 1 | +const crypto = require('crypto'); |
| 2 | +const childProcess = require('child_process'); |
| 3 | +const fs = require('fs'); |
| 4 | +const path = require('path'); |
| 5 | + |
| 6 | +const Jimp = require('jimp'); |
| 7 | + |
| 8 | +const imageDiff = require('../'); |
| 9 | + |
| 10 | +function hashFunction(data) { |
| 11 | + return crypto |
| 12 | + .createHash('md5') |
| 13 | + .update(data) |
| 14 | + .digest('hex'); |
| 15 | +} |
| 16 | + |
| 17 | +const snapshots = childProcess |
| 18 | + .execSync('ls snapshots', { encoding: 'utf-8' }) |
| 19 | + .split(/\n/) |
| 20 | + .filter(Boolean); |
| 21 | + |
| 22 | +jest.setTimeout(60000); |
| 23 | + |
| 24 | +describe('snapshot tests', () => { |
| 25 | + snapshots.forEach(snapshot => { |
| 26 | + it(snapshot, async () => { |
| 27 | + console.log('Starting', snapshot); |
| 28 | + const [image1, image2] = await Promise.all([ |
| 29 | + Jimp.read(path.resolve('snapshots', snapshot, 'before.png')), |
| 30 | + Jimp.read(path.resolve('snapshots', snapshot, 'after.png')), |
| 31 | + ]); |
| 32 | + console.log('Images ready', snapshot); |
| 33 | + const diffImage = imageDiff(image1.bitmap, image2.bitmap, { |
| 34 | + hashFunction, |
| 35 | + }); |
| 36 | + |
| 37 | + console.log('Created diff image', snapshot); |
| 38 | + const pathToDiff = path.resolve('snapshots', snapshot, 'diff.png'); |
| 39 | + |
| 40 | + if (!fs.existsSync(pathToDiff)) { |
| 41 | + console.log( |
| 42 | + `No previous diff image for ${snapshot} found -- saving diff.png.`, |
| 43 | + ); |
| 44 | + const newDiffImage = await new Jimp(diffImage); |
| 45 | + await newDiffImage.write(pathToDiff); |
| 46 | + } |
| 47 | + const expectedDiffImage = (await Jimp.read(pathToDiff)).bitmap; |
| 48 | + const diffHash = hashFunction(diffImage.data); |
| 49 | + const expectedHash = hashFunction(expectedDiffImage.data); |
| 50 | + if (diffHash !== expectedHash) { |
| 51 | + console.log( |
| 52 | + `Diff image did not match existing diff image. Remove this image and run again to re-generate:\n${pathToDiff}`, |
| 53 | + ); |
| 54 | + } |
| 55 | + expect(diffHash).toEqual(expectedHash); |
| 56 | + }); |
| 57 | + }); |
| 58 | +}); |
0 commit comments