-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
371 lines (332 loc) · 13.6 KB
/
index.js
File metadata and controls
371 lines (332 loc) · 13.6 KB
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
// Collect client and environment information
const sdkPkg = require('./package.json');
let seleniumPkg;
try {
seleniumPkg = require('selenium-webdriver/package.json');
} catch {
/* istanbul ignore next */
seleniumPkg = { name: 'unknown', version: 'unknown' };
}
const CLIENT_INFO = `${sdkPkg.name}/${sdkPkg.version}`;
const ENV_INFO = `${seleniumPkg.name}/${seleniumPkg.version}`;
const utils = require('@percy/sdk-utils');
const { DriverMetadata } = require('./driverMetadata');
const log = utils.logger('selenium-webdriver');
const CS_MAX_SCREENSHOT_LIMIT = 25000;
const SCROLL_DEFAULT_SLEEP_TIME = 0.45; // 450ms
const getWidthsForMultiDOM = (userPassedWidths, eligibleWidths) => {
// Deep copy of eligible mobile widths
let allWidths = [];
if (eligibleWidths?.mobile?.length !== 0) {
allWidths = allWidths.concat(eligibleWidths?.mobile);
}
if (userPassedWidths.length !== 0) {
allWidths = allWidths.concat(userPassedWidths);
} else {
allWidths = allWidths.concat(eligibleWidths.config);
}
return [...new Set(allWidths)].filter(e => e); // Removing duplicates
};
async function changeWindowDimensionAndWait(driver, width, height, resizeCount) {
try {
const caps = await driver.getCapabilities();
if (typeof driver?.sendDevToolsCommand === 'function' && caps.getBrowserName() === 'chrome' && process.env.PERCY_DISABLE_CDP_RESIZE !== 'true') {
await driver?.sendDevToolsCommand('Emulation.setDeviceMetricsOverride', {
height,
width,
deviceScaleFactor: 1,
mobile: false
});
} else {
await driver.manage().window().setRect({ width, height });
}
} catch (e) {
log.debug(`Resizing using CDP failed, falling back to driver resize for width ${width}`, e);
await driver.manage().window().setRect({ width, height });
}
try {
await driver.wait(async () => {
/* istanbul ignore next: no instrumenting injected code */
await driver.executeScript('return window.resizeCount') === resizeCount;
}, 1000);
} catch (e) {
log.debug(`Timed out waiting for window resize event for width ${width}`, e);
}
}
// Captures responsive DOM snapshots across different widths
async function captureResponsiveDOM(driver, options) {
const widths = getWidthsForMultiDOM(options.widths || [], utils.percy?.widths);
const domSnapshots = [];
const windowSize = await driver.manage().window().getRect();
let currentWidth = windowSize.width; let currentHeight = windowSize.height;
let lastWindowWidth = currentWidth;
let resizeCount = 0;
// Setup the resizeCount listener if not present
/* istanbul ignore next: no instrumenting injected code */
await driver.executeScript('PercyDOM.waitForResize()');
let height = currentHeight;
if (process.env.PERCY_RESPONSIVE_CAPTURE_MIN_HEIGHT) {
height = await driver.executeScript(`return window.outerHeight - window.innerHeight + ${utils.percy?.config?.snapshot?.minHeight}`);
}
for (let width of widths) {
if (lastWindowWidth !== width) {
resizeCount++;
await changeWindowDimensionAndWait(driver, width, height, resizeCount);
lastWindowWidth = width;
}
if (process.env.PERCY_RESPONSIVE_CAPTURE_RELOAD_PAGE) {
await driver.navigate().refresh();
await driver.executeScript(await utils.fetchPercyDOM());
}
if (process.env.RESPONSIVE_CAPTURE_SLEEP_TIME) {
await new Promise(resolve => setTimeout(resolve, parseInt(process.env.RESPONSIVE_CAPTURE_SLEEP_TIME) * 1000));
}
if (process.env.PERCY_ENABLE_LAZY_LOADING_SCROLL) {
await module.exports.slowScrollToBottom(driver);
}
let domSnapshot = await captureSerializedDOM(driver, options);
domSnapshot.width = width;
domSnapshots.push(domSnapshot);
}
// Reset window size back to original dimensions
await changeWindowDimensionAndWait(driver, currentWidth, currentHeight, resizeCount + 1);
return domSnapshots;
}
function ignoreCanvasSerializationErrors(options) {
return options?.ignoreCanvasSerializationErrors ??
utils.percy?.config?.snapshot?.ignoreCanvasSerializationErrors ??
false;
}
function ignoreStyleSheetSerializationErrors(options) {
return options?.ignoreStyleSheetSerializationErrors ??
utils.percy?.config?.snapshot?.ignoreStyleSheetSerializationErrors ??
false;
}
async function captureSerializedDOM(driver, options) {
/* istanbul ignore next: no instrumenting injected code */
let { domSnapshot } = await driver.executeScript(async (options) => ({
/* eslint-disable-next-line no-undef */
domSnapshot: await PercyDOM.serialize(options)
}), {
...options,
ignoreCanvasSerializationErrors: ignoreCanvasSerializationErrors(options),
ignoreStyleSheetSerializationErrors: ignoreStyleSheetSerializationErrors(options)
});
/* istanbul ignore next: no instrumenting injected code */
domSnapshot.cookies = await driver.manage().getCookies() || [];
return domSnapshot;
}
function isResponsiveDOMCaptureValid(options) {
if (utils.percy?.config?.percy?.deferUploads) {
return false;
}
return (
options?.responsive_snapshot_capture ||
options?.responsiveSnapshotCapture ||
utils.percy?.config?.snapshot?.responsiveSnapshotCapture ||
false
);
}
async function captureDOM(driver, options = {}) {
const responsiveSnapshotCapture = isResponsiveDOMCaptureValid(options);
if (responsiveSnapshotCapture) {
return await captureResponsiveDOM(driver, options);
} else {
return await captureSerializedDOM(driver, options);
}
}
async function currentURL(driver, options) {
/* istanbul ignore next: no instrumenting injected code */
let { url } = await driver.executeScript(options => ({
/* eslint-disable-next-line no-undef */
url: document.URL
}), options);
return url;
}
const createRegion = function({
boundingBox = null,
elementXpath = null,
elementCSS = null,
padding = null,
algorithm = 'ignore',
diffSensitivity = null,
imageIgnoreThreshold = null,
carouselsEnabled = null,
bannersEnabled = null,
adsEnabled = null,
diffIgnoreThreshold = null
} = {}) {
const elementSelector = {};
if (boundingBox) elementSelector.boundingBox = boundingBox;
if (elementXpath) elementSelector.elementXpath = elementXpath;
if (elementCSS) elementSelector.elementCSS = elementCSS;
const region = {
algorithm,
elementSelector
};
if (padding) {
region.padding = padding;
}
const configuration = {};
if (['standard', 'intelliignore'].includes(algorithm)) {
if (diffSensitivity !== null) configuration.diffSensitivity = diffSensitivity;
if (imageIgnoreThreshold !== null) configuration.imageIgnoreThreshold = imageIgnoreThreshold;
if (carouselsEnabled !== null) configuration.carouselsEnabled = carouselsEnabled;
if (bannersEnabled !== null) configuration.bannersEnabled = bannersEnabled;
if (adsEnabled !== null) configuration.adsEnabled = adsEnabled;
}
if (Object.keys(configuration).length > 0) {
region.configuration = configuration;
}
const assertion = {};
if (diffIgnoreThreshold !== null) {
assertion.diffIgnoreThreshold = diffIgnoreThreshold;
}
if (Object.keys(assertion).length > 0) {
region.assertion = assertion;
}
return region;
};
// Take a DOM snapshot and post it to the snapshot endpoint
const percySnapshot = async function percySnapshot(driver, name, options) {
if (!driver) throw new Error('An instance of the selenium driver object is required.');
if (!name) throw new Error('The `name` argument is required.');
if (!(await module.exports.isPercyEnabled())) {
if (process.env.PERCY_RAISE_ERROR === 'true') {
throw new Error('Percy is not running, disabling snapshots.');
} else {
return;
}
}
if (utils.percy?.type === 'automate') {
throw new Error('Invalid function call - percySnapshot(). Please use percyScreenshot() function while using Percy with Automate. For more information on usage of percyScreenshot, refer https://www.browserstack.com/docs/percy/integrate/functional-and-visual');
}
try {
// Inject the DOM serialization script
await driver.executeScript(await utils.fetchPercyDOM());
// Serialize and capture the DOM
/* istanbul ignore next: no instrumenting injected code */
let domSnapshot = await captureDOM(driver, options);
let url = await currentURL(driver, options);
// Post the DOM to the snapshot endpoint with snapshot options and other info
const response = await utils.postSnapshot({
...options,
environmentInfo: ENV_INFO,
clientInfo: CLIENT_INFO,
domSnapshot,
name,
url
});
return response?.body?.data;
} catch (error) {
// Handle errors
log.error(`Could not take DOM snapshot "${name}"`);
log.error(error);
if (process.env.PERCY_RAISE_ERROR === 'true') {
throw error;
}
}
};
module.exports = percySnapshot;
module.exports.percySnapshot = percySnapshot;
module.exports.createRegion = createRegion;
module.exports.request = async function request(data) {
return await utils.captureAutomateScreenshot(data);
}; // To mock in test case
const getElementIdFromElements = async function getElementIdFromElements(elements) {
return Promise.all(elements.map(e => e.getId()));
};
module.exports.percyScreenshot = async function percyScreenshot(driver, name, options) {
if (!driver || typeof driver === 'string') {
// Unable to test this as couldnt define `browser` from test mjs file
try {
// browser is defined in wdio context
// eslint-disable-next-line no-undef
[driver, name, options] = [browser, driver, name];
} catch (e) { // ReferenceError: browser is not defined.
driver = undefined;
}
}
if (!driver) throw new Error('An instance of the selenium driver object is required.');
if (!name) throw new Error('The `name` argument is required.');
if (!(await module.exports.isPercyEnabled())) {
if (process.env.PERCY_RAISE_ERROR === 'true') {
throw new Error('Percy is not running, disabling snapshots.');
} else {
return;
}
}
if (utils.percy?.type !== 'automate') {
throw new Error('Invalid function call - percyScreenshot(). Please use percySnapshot() function for taking screenshot. percyScreenshot() should be used only while using Percy with Automate. For more information on usage of PercySnapshot(), refer doc for your language https://www.browserstack.com/docs/percy/integrate/overview');
}
try {
const driverData = new DriverMetadata(driver);
if (options) {
if ('ignoreRegionSeleniumElements' in options) {
options.ignore_region_selenium_elements = options.ignoreRegionSeleniumElements;
delete options.ignoreRegionSeleniumElements;
}
if ('considerRegionSeleniumElements' in options) {
options.consider_region_selenium_elements = options.considerRegionSeleniumElements;
delete options.considerRegionSeleniumElements;
}
if ('ignore_region_selenium_elements' in options) {
options.ignore_region_selenium_elements = await getElementIdFromElements(options.ignore_region_selenium_elements);
}
if ('consider_region_selenium_elements' in options) {
options.consider_region_selenium_elements = await getElementIdFromElements(options.consider_region_selenium_elements);
}
}
// Post the driver details to the automate screenshot endpoint with snapshot options and other info
const response = await module.exports.request({
environmentInfo: ENV_INFO,
clientInfo: CLIENT_INFO,
sessionId: await driverData.getSessionId(),
commandExecutorUrl: await driverData.getCommandExecutorUrl(),
capabilities: await driverData.getCapabilities(),
snapshotName: name,
options
});
return response?.body?.data;
} catch (error) {
// Handle errors
log.error(`Could not take Screenshot "${name}"`);
log.error(error.stack);
if (process.env.PERCY_RAISE_ERROR === 'true') {
throw error;
}
}
};
// jasmine cannot mock individual functions, hence adding isPercyEnabled to the exports object
// also need to define this at the end of the file or else default exports will over-ride this
module.exports.isPercyEnabled = async function isPercyEnabled() {
return await utils.isPercyEnabled();
};
module.exports.slowScrollToBottom = async (driver, scrollSleep = SCROLL_DEFAULT_SLEEP_TIME) => {
if (process.env.PERCY_LAZY_LOAD_SCROLL_TIME) {
scrollSleep = parseFloat(process.env.PERCY_LAZY_LOAD_SCROLL_TIME);
}
const scrollHeightCommand = 'return Math.max(document.body.scrollHeight, document.body.clientHeight, document.body.offsetHeight, document.documentElement.scrollHeight, document.documentElement.clientHeight, document.documentElement.offsetHeight);';
let scrollHeight = Math.min(await driver.executeScript(scrollHeightCommand), CS_MAX_SCREENSHOT_LIMIT);
const clientHeight = await driver.executeScript('return document.documentElement.clientHeight');
let current = 0;
let page = 1;
// Break the loop if maximum scroll height 25000px is reached
while (scrollHeight > current && current < CS_MAX_SCREENSHOT_LIMIT) {
current = clientHeight * page;
page += 1;
await driver.executeScript(`window.scrollTo(0, ${current})`);
await new Promise(resolve => setTimeout(resolve, scrollSleep * 1000));
// Recalculate scroll height for dynamically loaded pages
scrollHeight = await driver.executeScript(scrollHeightCommand);
}
// Get back to top
if (!(process.env.BYPASS_SCROLL_TO_TOP === 'true')) {
await driver.executeScript('window.scrollTo(0, 0)');
}
let sleepAfterScroll = 1;
if (process.env.PERCY_SLEEP_AFTER_LAZY_LOAD_COMPLETE) {
sleepAfterScroll = parseFloat(process.env.PERCY_SLEEP_AFTER_LAZY_LOAD_COMPLETE);
}
await new Promise(resolve => setTimeout(resolve, sleepAfterScroll * 1000));
};