-
Notifications
You must be signed in to change notification settings - Fork 14
/
snapshot-testing.js
68 lines (59 loc) · 1.61 KB
/
snapshot-testing.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
const fs = require('fs');
const { promisify } = require('util');
const { chromium } = require('playwright');
const pixelmatch = require('pixelmatch');
const { PNG } = require('pngjs');
const config = {
viewport: {
width: 1920,
height: 1080,
},
};
const fsStat = promisify(fs.stat);
const fsCopyFile = promisify(fs.copyFile);
const imageFromFile = (filename) =>
new Promise((resolve) => {
const img = fs
.createReadStream(filename)
.pipe(new PNG())
.on('parsed', () => {
resolve(img.data);
});
});
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
page.setViewportSize({ ...config.viewport });
await page.goto('https://fireship.io/');
await page.waitForTimeout(2000);
// capture the screenshot
await page.screenshot({ path: 'new_layout.png' });
const oldFile = await fsStat('old_layout.png').catch(() => undefined);
if (!oldFile) {
console.log('no old layout, exiting');
await fsCopyFile('new_layout.png', 'old_layout.png');
await browser.close();
return;
}
const newLayout = await imageFromFile('new_layout.png');
const oldLayout = await imageFromFile('old_layout.png');
const diff = new PNG(config.viewport);
const diffPixels = pixelmatch(
newLayout,
oldLayout,
diff.data,
config.viewport.width,
config.viewport.height,
{
threshold: 0,
},
);
if (diffPixels === 0) {
console.log('Success! No difference in rendering');
} else {
console.log(
`Uh-oh! There are ${diffPixels} different pixels in new render!`,
);
}
await browser.close();
})();