This repository has been archived by the owner on Jul 21, 2022. It is now read-only.
forked from rsamec/karma-puppeteer-launcher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
395 lines (353 loc) · 11.6 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
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
var path = require("path");
var puppeteer = require("puppeteer-core");
var fs = require("fs");
var DEFAULT_CMD = require("./chrome");
var PNG = require("pngjs").PNG;
var pixelmatch = require("pixelmatch");
var dynamicpixelmatch = require("dynamicpixelmatch");
function isJSFlags(flag) {
return flag.indexOf("--js-flags=") === 0;
}
function sanitizeJSFlags(flag) {
var test = /--js-flags=(['"])/.exec(flag);
if (!test) {
return flag;
}
var escapeChar = test[1];
var endExp = new RegExp(escapeChar + "$");
var startExp = new RegExp("--js-flags=" + escapeChar);
return flag.replace(startExp, "--js-flags=").replace(endExp, "");
}
var ChromeBrowser = function (baseBrowserDecorator, args) {
baseBrowserDecorator(this);
var flags = args.flags || [];
var userDataDir = args.chromeDataDir || this._tempDir;
this._getOptions = function (url) {
// Chrome CLI options
// http://peter.sh/experiments/chromium-command-line-switches/
flags.forEach(function (flag, i) {
if (isJSFlags(flag)) {
flags[i] = sanitizeJSFlags(flag);
}
});
return [
"--user-data-dir=" + userDataDir,
"--no-default-browser-check",
"--no-first-run",
"--disable-gpu",
"--font-render-hinting=none",
"--disable-default-apps",
"--disable-popup-blocking",
"--disable-translate",
"--disable-background-timer-throttling",
].concat(flags, [url]);
};
};
const ensureExists = function (path, mask) {
return new Promise((resolve, reject) => {
if (typeof mask == "function") {
// allow the `mask` parameter to be optional
//cb = mask;
mask = 0777;
}
fs.mkdir(path, mask, function (err) {
if (err) {
if (err.code == "EEXIST")
resolve("ignore the error if the folder already exists");
else reject(err); // something else went wrong
}
resolve("file created successfully with handcrafted Promise!");
});
});
};
const ensureExistsFromRoot = async (root, paths) => {
var rootPath = root;
await ensureExists(rootPath);
for (var i = 0; i < paths.length - 1; i++) {
rootPath = path.resolve(rootPath, paths[i]);
await ensureExists(rootPath);
}
};
const fileExists = (path) => {
return new Promise((resolve, reject) => {
fs.access(path, fs.F_OK, (err) => {
if (err) {
resolve(false);
}
resolve(true);
});
});
};
const DEFAULT_TARGET_DIR = "target";
const DEFAULT_SCREENSHOT_GOLDEN_DIR = "golden";
const DEFAULT_SCREENSHOT_DIR = "screenshots";
const DEFAULT_SCREENSHOT_DIFF_DIR = "diff";
const screenshotRootpaths = ["./", DEFAULT_TARGET_DIR, DEFAULT_SCREENSHOT_DIR];
const goldenRootpaths = [
"./",
DEFAULT_TARGET_DIR,
DEFAULT_SCREENSHOT_GOLDEN_DIR,
];
const diffRootpaths = ["./", DEFAULT_TARGET_DIR, DEFAULT_SCREENSHOT_DIFF_DIR];
const getGoldenScreenshotPath = (paths) =>
path.resolve(...goldenRootpaths.concat(paths));
const getScrenshotPath = (paths) =>
path.resolve(...screenshotRootpaths.concat(paths));
const getDiffScrenshotPath = (paths) =>
path.resolve(...diffRootpaths.concat(paths));
const compareScreenshots = async (paths, excluded, threshold) => {
return new Promise(async (resolve, reject) => {
doneReading = async () => {
// Wait until both files are read.
if (++filesRead < 2) return;
// The files should be the same size.
if (img1.width != img2.width) {
// console.error("image widths are not the same");
resolve(false);
}
if (img1.height != img2.height) {
// console.error("image heights are not the same");
resolve(false);
}
// Do the visual diff.
const diff = new PNG({ width: img1.width, height: img2.height });
const matchOptions = { threshold: threshold || 0.3 };
const numDiffPixels =
excluded != null && excluded.length != 0
? dynamicpixelmatch(
img1.data,
img2.data,
diff.data,
img1.width,
img1.height,
matchOptions,
excluded
)
: pixelmatch(
img1.data,
img2.data,
diff.data,
img1.width,
img1.height,
matchOptions
);
// The files should look the same.
if (numDiffPixels != 0) {
// console.error("number of different pixels are not 0");
await ensureExistsFromRoot(path.resolve(...diffRootpaths), paths);
diff.pack().pipe(fs.createWriteStream(getDiffScrenshotPath(paths)));
resolve(false);
}
resolve(true);
};
const img1 = fs
.createReadStream(getGoldenScreenshotPath(paths))
.pipe(new PNG())
.on("parsed", await doneReading);
const img2 = fs
.createReadStream(getScrenshotPath(paths))
.pipe(new PNG())
.on("parsed", await doneReading);
let filesRead = 0;
});
};
var PuppeteerBrowser = function (baseBrowserDecorator, args) {
ChromeBrowser.apply(this, arguments);
var flags = args.flags || [];
var browser;
this._start = async (url) => {
// console.log(url);
await ensureExists(path.resolve("./", DEFAULT_TARGET_DIR));
await ensureExists(
path.resolve("./", DEFAULT_TARGET_DIR, DEFAULT_SCREENSHOT_DIR)
);
browser = await puppeteer.launch({
headless: flags.indexOf("--headless") != -1,
args: flags,
executablePath: DEFAULT_CMD[process.platform],
});
const page = await browser.newPage();
// Capture logging
// page.on('console', (...args) => console.log.apply(console, ['[Browser]', ...args]));
// Expose Screenshot function
await page.exposeFunction("capturePage", (name, clip) => {
const filename = path.resolve(
"./",
DEFAULT_TARGET_DIR,
DEFAULT_SCREENSHOT_DIR,
`${name}.png`
);
// console.log("[Node]", "Save 🎨 to", filename);
return page.screenshot(
clip !== undefined
? { path: filename, clip: clip }
: { path: filename, fullPage: true }
);
});
await page.exposeFunction("waitForNavigation", async (options) => {
await page.waitForNavigation(options);
});
await page.exposeFunction("waitForFunction", async (options) => {
await page.waitForFunction(options);
});
await page.exposeFunction("pressKey", async (key, times, options) => {
for (let i=0; i<times; i++) {
await page.keyboard.press(key, options);
}
});
await page.exposeFunction("typeInto", async (selector, text, replace=false) => {
const frame = await page.frames().find((f) => f.name() === "context");
const element = await frame.$(selector);
await element.click({clickCount: replace ? 3 : 1});
await page.keyboard.type(text);
});
await page.exposeFunction("type", async (text) => {
await page.keyboard.type(text);
});
await page.exposeFunction("click", async (selector) => {
const frame = await page.frames().find((f) => f.name() === "context");
const element = await frame.$(selector);
await element.click({});
});
await page.exposeFunction("waitForSelector", async (selector, options) => {
await page.waitForSelector(selector, options);
});
await page.exposeFunction("puppeteerDone", async (code) => {
await browser.close();
process.exit(code);
});
await page.exposeFunction("setViewport", async (options) => {
await page.setViewport(options);
});
await page.exposeFunction("captureElement", async (name, selector) => {
const filename = path.resolve(
"./",
DEFAULT_TARGET_DIR,
DEFAULT_SCREENSHOT_DIR,
`${name}.png`
);
const frame = await page.frames().find((f) => f.name() === "context");
const element = await frame.$(selector);
await element.screenshot({ path: filename });
});
const screenshotPage = async (paths, golden, clip) => {
await ensureExistsFromRoot(
golden
? path.resolve(...goldenRootpaths)
: path.resolve(...screenshotRootpaths),
paths
);
const filename = golden
? getGoldenScreenshotPath(paths)
: getScrenshotPath(paths);
// console.log("[Node]", "Save 🎨 to", filename);
return page.screenshot(
clip !== undefined
? { path: filename, clip: clip }
: { path: filename, fullPage: true }
);
};
const screenshotElement = async (paths, selector, golden) => {
await ensureExistsFromRoot(
golden
? path.resolve(...goldenRootpaths)
: path.resolve(...screenshotRootpaths),
paths
);
const filename = golden
? getGoldenScreenshotPath(paths)
: getScrenshotPath(paths);
const frame = await page.frames().find((f) => f.name() === "context");
const element = await frame.$(selector);
await element.screenshot({ path: filename });
};
await page.exposeFunction("waitFor", (millis) => {
return new Promise(async (resolve, reject) => {
await page.waitFor(millis);
resolve();
});
});
await page.exposeFunction("hover", (selector) => {
return new Promise(async (resolve, reject) => {
await page.hover(selector);
resolve();
});
});
await page.exposeFunction("moveMouse", (x, y) => {
return new Promise(async (resolve, reject) => {
await page.mouse.move(x,y);
resolve();
});
});
await page.exposeFunction("addStyleTag", (content) => {
return new Promise(async (resolve, reject) => {
await page.addStyleTag({content});
resolve();
});
});
await page.exposeFunction(
"matchPageSnapshot",
(paths, clip, excluded, threshold) => {
return new Promise(async (resolve, reject) => {
// await page.waitFor(300);
var update = flags.indexOf("--snapshot-update") != -1;
if (update) {
await screenshotPage(paths, true, clip);
resolve(true);
} else {
const snapshotExists = await fileExists(
getGoldenScreenshotPath(paths)
);
if (!snapshotExists) {
await screenshotPage(paths, true, clip);
resolve(true);
} else {
await screenshotPage(paths, false, clip);
resolve(await compareScreenshots(paths, excluded, threshold));
}
}
});
}
);
await page.exposeFunction(
"matchElementSnapshot",
(paths, selector, excluded) => {
return new Promise(async (resolve, reject) => {
var update = flags.indexOf("--snapshot-update") != -1;
if (update) {
await screenshotElement(paths, selector, true);
resolve(true);
} else {
const snapshotExists = await fileExists(
getGoldenScreenshotPath(paths)
);
if (!snapshotExists) {
await screenshotElement(paths, selector, true);
resolve(true);
} else {
await screenshotElement(paths, selector, false);
resolve(await compareScreenshots(paths, excluded));
}
}
});
}
);
await page.goto(url);
};
this.on("kill", async (done) => {
if (browser != null) {
await browser.close();
}
done();
});
};
PuppeteerBrowser.prototype = {
name: "Puppeteer",
DEFAULT_CMD: {},
ENV_CMD: "PUPPETEER_BIN",
};
PuppeteerBrowser.$inject = ["baseBrowserDecorator", "args"];
// PUBLISH DI MODULE
module.exports = {
"launcher:Puppeteer": ["type", PuppeteerBrowser],
};