-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
70 lines (62 loc) · 1.54 KB
/
index.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
69
70
import { join } from '@dword-design/functions'
import fs from 'fs-extra'
import pixelmatch from 'pixelmatch'
import { PNG } from 'pngjs'
export const toMatchImage = (received, expected, options = {}) => {
if (typeof expected === 'string') {
expected = fs.readFileSync(expected)
}
const img1 = PNG.sync.read(received)
const img2 = PNG.sync.read(expected)
const diffImg = new PNG({ height: img1.height, width: img1.width })
const diff = pixelmatch(
img1.data,
img2.data,
diffImg.data,
img1.width,
img1.height
)
const compositeImg = new PNG({ height: img1.height, width: 3 * img1.width })
PNG.bitblt(img1, compositeImg, 0, 0, img1.width, img1.height, 0, 0)
PNG.bitblt(
diffImg,
compositeImg,
0,
0,
img1.width,
img1.height,
img1.width,
0
)
PNG.bitblt(
img2,
compositeImg,
0,
0,
img1.width,
img1.height,
2 * img1.width,
0
)
const pass = diff === 0
if (!pass && options.diffPath) {
fs.writeFileSync(options.diffPath, PNG.sync.write(compositeImg))
}
return {
message: () =>
pass
? 'Expected the images to differ, but they are equal.'
: [
`Expected the images to be equal, but they differ by ${diff} pixels.`,
...(options.dumpDiffToConsole
? [
'',
`data:image/png;base64,${PNG.sync
.write(compositeImg)
.toString('base64')}`,
]
: []),
] |> join('\n'),
pass,
}
}