This repository was archived by the owner on Aug 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathhelpers.js
executable file
·313 lines (267 loc) · 10.6 KB
/
helpers.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
var urlParser = require('url');
const fs = require('fs-extra');
const PNG = require('pngjs').PNG;
const pixelmatch = require('pixelmatch');
module.exports = {
/**
* returns a promise that is called when the url has loaded and the body element is present
* @param {string} url - url to load
* @param {integer} waitInSeconds - number of seconds to wait for page to load
* @returns {Promise} resolved when url has loaded otherwise rejects
* @example
* await helpers.loadPage('http://www.google.com');
*/
loadPage: function(url, waitInSeconds) {
// use either passed in timeout or global default
var timeout = (waitInSeconds) ? (waitInSeconds * 1000) : DEFAULT_TIMEOUT;
// load the url and wait for all requests to end
return page.goto(url, { timeout: timeout, waitUntil: 'networkidle0' });
},
/**
* Opens URL in a new tab and set it as the current page, if the URL is
* already open in another tab in the current browser then we will use
* that instead of opening a new one.
* @param {string} url - url to open (or find in existing tab)
* @param {object} options - puppeteer page.goto options
* @returns {Promise} resolves once new sheet open or focused
*/
openPage: async function (url, options) {
// URLs returned from Chrome always have a trailing /
// So convert incoming URL to match (converts urlParser.parse('https://api.com?23234234').format() to 'https://api.com/?23234234')
url = urlParser.parse(url).format();
const pages = await browser.pages();
page = pages.find(page => page.url() === url);
/**
* We've not been able to find the page in current browser instance,
* so lets open one and navigate to the url.
*/
if (page === undefined) {
page = await browser.newPage();
await page.goto(url, {
timeout: DEFAULT_TIMEOUT,
waitUntil: 'networkidle0',
...options
});
}
/**
* Set the global page and bring to front.
*/
page.bringToFront();
},
/**
* Removes an element from the dom
* @param {string} selector - query selector
* @returns {Promise} resolves when complete
* @example
* await helpers.removeElement('p > span');
*/
removeElement: function(selector) {
return page.evaluate(function(elementSelector) {
var el = document.querySelector(elementSelector);
if (el) el.remove();
}, selector);
},
/**
* Waits for text to appear on the page
* @param {string} text - text to find
* @param {boolean} exact - exact match if true, otherwise partial
* @param {integer} waitInSeconds - number of seconds to wait before giving up
* @returns {Promise} resolves when complete
* @example
* await helpers.waitForLinkText('Orca Scan', false, 30);
*/
waitForLinkText: function(text, exact, waitInSeconds) {
// use either passed in timeout or global default
var timeout = (waitInSeconds) ? (waitInSeconds * 1000) : DEFAULT_TIMEOUT;
return page.waitForFunction(function(textToFind, exactMatch) {
return Array.prototype.slice.call(document.querySelectorAll('a')).some(function(link) {
if (exactMatch) {
return link.textContent === textToFind;
}
return link.textContent.indexOf(textToFind) > -1;
});
}, { timeout: timeout }, text, exact);
},
/**
* Wait for the browser to fire an event (including custom events)
* @param {string} eventName - Event name
* @param {integer} waitInSeconds - number of seconds to wait
* @returns {Promise} resolves when event fires or timeout is reached
* @example
* await helpers.waitForEvent('app-ready');
*/
waitForEvent: async function(eventName, waitInSeconds) {
// use either passed in timeout or global default
var timeout = (waitInSeconds) ? (waitInSeconds * 1000) : DEFAULT_TIMEOUT;
// use race to implement a timeout
return Promise.race([
// add event listener and wait for event to fire before returning
page.evaluate(function(eventName) {
return new Promise(function(resolve, reject) {
document.addEventListener(eventName, function(e) {
resolve(); // resolves when the event fires
});
});
}, eventName),
// if the event does not fire within n seconds, exit
page.waitForTimeout(timeout)
]);
},
/**
* Gets an element within an iframe
* @param {string} frameSelector - query selector for the iframe element
* @param {string} childSelector - query selector for the child within the iframe
* @returns {Promise} returns element if found otherwise rejects with an error
* @example
* await helpers.getElementWithinFrame('iframe[src*="consent.google.com"]', '#introAgreeButton > span > span');
*/
getElementWithinFrame: async function(frameSelector, childSelector) {
var elementHandle = await page.$(frameSelector);
if (elementHandle) {
var frame = await elementHandle.contentFrame();
if (frame) {
// as this is an iframe, wait for it to load by waiting for the selector to appear
await frame.waitForSelector(childSelector);
return frame.$(childSelector);
}
}
return Promise.reject('frame not found');
},
/**
* Clicks an element within an iframe
* @param {string} frameSelector - query selector for the iframe element
* @param {string} childSelector - query selector for the child within the iframe
* @returns {Promise} resolves when done otherwise throws an error
* @example
* await helpers.clickElementWithinFrame('iframe[src*="consent.google.com"]', '#introAgreeButton > span > span');
*/
clickElementWithinFrame: async function(frameSelector, childSelector) {
var el = await helpers.getElementWithinFrame(frameSelector, childSelector);
if (el) {
return el.click();
}
return Promise.reject('element not found');
},
/**
* Removes all browser cookies
* @returns {Promise} resolves once done
* @example
* await helpers.clearCookies();
*/
clearCookies: function() {
return page.evaluate(function() {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
var eqPos = cookie.indexOf('=');
var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = name + '=;' +
'expires=Thu, 01-Jan-1970 00:00:01 GMT;' +
'path=/;' +
'domain=' + window.location.host + ';' +
'secure=;';
}
});
},
/**
* Clears localStorage
* @returns {Promise} resolves once done
* @example
* await helpers.clearLocalStorage();
*/
clearLocalStorage: function() {
return page.evaluate(function() {
window.localStorage.clear();
});
},
/**
* Clears sessionStorage
* @returns {Promise} resolves once done
* @example
* await helpers.clearSessionStorage();
*/
clearSessionStorage: function() {
return page.evaluate(function() {
window.sessionStorage.clear();
});
},
/**
* Clears cookies and storage
* @returns {Promise} resolves once done
* @example
* await helpers.clearCookiesAndStorages();
*/
clearCookiesAndStorages: async function() {
await helpers.clearCookies();
await helpers.clearLocalStorage();
await helpers.clearSessionStorage();
},
/**
* Stop the browser in debug mode
* @returns {Promise} resolves once done
* @example
* await helpers.debug();
*/
debug: function() {
if (devTools === true) {
return page.evaluate('debugger');
}
return Promise.reject(new Error('DevTools must be enabled to use helpers.debug(). Enable DevTools using the -devTools switch'));
},
/**
* Visual comparison function
* @param fileName
* @returns {Promise<void>}
*/
compareImage: async (fileName) => {
const verify = require('./imageCompare');
await verify.assertion(fileName);
await verify.value();
await verify.pass();
},
/**
* @param fileName
* @param elementsToHide
* @returns {Promise<void>}
*/
takeImage: async (fileName, elementsToHide) => {
const verify = require('./imageCompare');
await verify.takeScreenshot(fileName, elementsToHide);
},
/**
* hideElemements hide elements
* @param selectors
*/
hideElements: async (selectors) => {
selectors = typeof selectors === 'string' ? [selectors] : selectors;
for (let i = 0; i < selectors.length; i++) {
const script = `document.querySelectorAll('${selectors[i]}').forEach(element => element.style.opacity = '0')`;
await browser.execute(script);
}
},
/**
* showElemements show elements
* @param selectors
*/
showElements: async (selectors) => {
selectors = typeof selectors === 'string' ? [selectors] : selectors;
for (let i = 0; i < selectors.length; i++) {
const script = `document.querySelectorAll('${selectors[i]}').forEach(element => element.style.opacity = '1')`;
await browser.execute(script);
}
},
/**
* Returns number of pixels that are different between two images
* @param {string} fileName1 - name of the first file
* @param {string} fileName2 - name of the second file
* @returns
*/
numDiffPixels: async (fileName1, fileName2) => {
const img1 = PNG.sync.read(fs.readFileSync('./artifacts/visual-regression/original/chrome/positive/' + fileName1 + '.png'));
const img2 = PNG.sync.read(fs.readFileSync('./artifacts/visual-regression/original/chrome/positive/' + fileName2 + '.png'));
const { width, height } = img1;
const diff = new PNG({ width, height });
const numDiffPixels = pixelmatch(img1.data, img2.data, diff.data, width, height, { threshold: 0.1 });
return numDiffPixels;
}
};