/
chromyRunner.js
101 lines (95 loc) · 3.09 KB
/
chromyRunner.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
import fs from 'fs';
import Chromy from 'chromy';
import logger from './logger';
import compareImage from './compareImage';
import actions from './actions';
import { configTypes } from './defaultConfig';
const CHROME_PORT = 9222;
const CHROME_WIDTH = 800;
const CHROME_HEIGHT = 600;
const saveImage = (filename, image, testType, screenshotsPath, testReportPath) => {
if (testType === configTypes.test) {
logger.log(`screenshot saved in -> ${testReportPath}/${filename}.png`);
return fs.writeFileSync(`${testReportPath}/${filename}.png`, image);
}
logger.log(`screenshot saved in -> ${screenshotsPath}/${filename}.png`);
return fs.writeFileSync(`${screenshotsPath}/${filename}.png`, image);
};
class ChromyRunner {
constructor(options) {
this.options = options;
this.currentTestId = 0;
}
async _stepRunner(chromy, test) {
/* eslint-disable no-restricted-syntax */
for (const action of test.steps) {
/* eslint-enable no-restricted-syntax */
switch (action.name) {
case actions.goto:
try {
await chromy.goto(action.value);
logger.log(`goto -> ${action.value}`);
} catch (error) {
logger.error(error);
return false;
}
break;
case actions.capture:
if (action.value === 'document') {
try {
const png = await chromy.screenshotDocument();
await saveImage(test.name, png, test.type, this.options.screenshots, this.options.testReportPath);
} catch (error) {
logger.error(error);
return false;
}
} else {
try {
const png = await chromy.screenshotSelector(action.value);
await saveImage(test.name, png, test.type, this.options.screenshots, this.options.testReportPath);
} catch (error) {
logger.error(error);
return false;
}
}
break;
case actions.test:
try {
const result = await compareImage(this.options, test.name);
logger.log(result);
logger.log(`campare -> ${this.options.testReportPath}/${test.name}.png
and ${this.options.screenshots}/${test.name}.png`);
} catch (error) {
logger.error(error);
return false;
}
break;
default:
break;
}
}
return true;
}
async run(test) {
const width = test.resolution.width || CHROME_WIDTH;
const height = test.resolution.height || CHROME_HEIGHT;
const flags = [`--window-size=${width},${height}`];
const chromy = new Chromy({
chromeFlags: flags,
port: CHROME_PORT + this.currentTestId,
waitTimeout: this.options.timeout,
visible: this.options.visible || false,
});
this.currentTestId += 1;
const result = await this._stepRunner(chromy, test);
logger.log('closing browser');
try {
chromy.close();
} catch (error) {
logger.error(error);
return false;
}
return result;
}
}
exports.ChromyRunner = ChromyRunner;