-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.ts
194 lines (160 loc) · 4.99 KB
/
index.ts
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import { Page, webkit } from 'playwright';
import handler from 'serve-handler';
import * as http from 'http';
import * as fs from 'fs';
import * as jimp from 'jimp';
import { getFilteredTestFolders } from './utils/files-utils';
import { pascalCase } from 'pascal-case';
import Webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';
import webpackConfig from './webpack.config';
import * as path from "path";
const { buildMainPage } = require('./utils/preBundle');
const HtmlWebpackPlugin = require('html-webpack-plugin');
interface ComparisonResult {
image: any;
percent: number;
distance: number;
}
const PORT = process.env.PORT || 3000;
const SERVER_URL = `http://localhost:${PORT}`;
const SNAPSHOT_PATH = './ui-tests/snapshots';
async function compareToSnapshot(page: Page, snapshotPath: string) {
const componentName = snapshotPath.substring(snapshotPath.lastIndexOf('/') + 1, snapshotPath.lastIndexOf('.'));
const tmpScreenshotPath = snapshotPath.replace(componentName, `${componentName}-snapshot`);
await takeSnapshot(page, tmpScreenshotPath);
const comparisonResult = await compareImages(snapshotPath, tmpScreenshotPath);
await comparisonResult.image.writeAsync(snapshotPath.replace(componentName, `${componentName}-diff`));
return comparisonResult;
}
async function compareImages(img1Path, img2Path): Promise<ComparisonResult> {
const img1 = await jimp.read(fs.readFileSync(img1Path));
const img2 = await jimp.read(fs.readFileSync(img2Path));
const diff = jimp.diff(img1, img2, 0.1);
const distance = jimp.distance(img1, img2);
return {
...diff,
distance
};
}
async function takeSnapshot(page, snapshotPath) {
const componentName = snapshotPath.substring(snapshotPath.lastIndexOf('/') + 1, snapshotPath.lastIndexOf('.'));
const elementId = `#${pascalCase(componentName)
.replace('Snapshot', '')}`;
const element = await page.$(elementId);
let screenShotHandler = element;
if (await element.getAttribute('testWholePage')) {
screenShotHandler = page;
}
return screenShotHandler.screenshot({
path: snapshotPath,
fullPage: true
});
}
function resultsMessage(diff, fixed = 2) {
return `Distance: ${diff.distance} | Percent: ${(diff.percent * 100).toFixed(fixed)} %`;
}
async function runImageComparison() {
const testedComponents = getFilteredTestFolders();
const browser = await webkit.launch();
for (const i in testedComponents) {
console.log(`Testing ${testedComponents[i]}`);
await runTestOnComponent(browser, testedComponents[i]);
}
console.log('Visual tests completed!');
await browser.close();
}
async function runTestOnComponent(browser, componentName) {
const pageInstance = await browser.newPage();
const testUrl = `${SERVER_URL}/${componentName}`;
pageInstance.goto(testUrl);
return new Promise((res) => {
pageInstance.context()
.exposeBinding('doTest', async ({ page }) => {
await doTest(page);
res(true);
});
});
}
async function doTest(page) {
const componentName = page.url()
.split('/')
.splice(-1, 1)[0];
const snapshotPath = `${SNAPSHOT_PATH}/${componentName}.png`;
await page.waitForLoadState('networkidle');
if (process.argv.includes('-u')) {
console.log('Updating snapshot...');
await (new Promise(res => setTimeout(res, 200)));
await takeSnapshot(page, snapshotPath);
} else {
if (!fs.existsSync(snapshotPath)) {
console.error(`Missing snapshot for ${componentName}`);
process.exitCode = 1;
return;
}
const diff = await compareToSnapshot(page, snapshotPath);
if (diff.percent <= 0.001) {
console.log('Visual Diff Passed!');
console.log(resultsMessage(diff));
} else {
console.error('Visual Diff Failed!');
console.error(resultsMessage(diff, 10));
process.exitCode = 1;
}
}
}
function finalizeTest(testsServer) {
// decide process exit code
testsServer.close();
}
async function setDevServer() {
await buildMainPage();
webpackConfig.plugins.push(new HtmlWebpackPlugin({
inject: false,
chunks: ['mainPage'],
filename: 'index.html',
template: path.join(__dirname, 'tmp/index.html.tmpl')
}));
const compiler = Webpack({
...webpackConfig,
mode: 'development'
});
const devServerOptions = {
...webpackConfig.devServer,
open: true
};
//@ts-ignore
const devServer = new WebpackDevServer(devServerOptions, compiler);
devServer.listen(webpackConfig.devServer.port, '127.0.0.1', () => {
console.log(`Starting server on http://localhost:${webpackConfig.devServer.port}`);
});
}
function runTests(port = PORT) {
const server = http.createServer((request, response) => {
return handler(request, response, {
public: 'ui-tests/dist'
});
});
return new Promise((res, rej) => {
server.listen(port, async () => {
console.log('Running at ', `http://localhost:${port}`);
try {
await runImageComparison();
} catch (e) {
console.error(e);
process.exitCode = 1;
server.close();
}
res(server);
});
});
}
async function main() {
if (!process.argv.includes('-s')) {
runTests()
.then(finalizeTest);
} else {
await setDevServer();
}
}
main().then(r => {});