forked from paypal/paypal-checkout-components
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.js
269 lines (218 loc) · 7.35 KB
/
common.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
/* @flow */
/* eslint no-console: off, import/no-nodejs-modules: off */
import { join } from 'path';
import puppeteer from 'puppeteer';
import { withMock, methods } from 'mocketeer';
import { HEADLESS, DEVTOOLS, DOMAIN, RETRIES, LOG, TIMEOUT } from './config';
export function log(...args : $ReadOnlyArray<mixed>) {
if (LOG) {
console.info(...args);
}
}
function normalizeString(str : string, reg : RegExp) : string {
return str.replace(reg, '_').replace(/^_+/, '').replace(/_+$/, '');
}
function getDate() : string {
return normalizeString(new Date().toISOString(), /[^0-9]+/g);
}
export async function screenshot(page : Object, name : string) : Promise<void> {
if (!page.screenshot && page._frameManager) {
page = page._frameManager.page();
}
await page.screenshot({
path: join(__dirname, 'screenshots', `${ getDate() }_${ normalizeString(name, /[^a-zA-Z_0-9-]+/g) }.png`)
});
}
export function logFailedRequests(page : Object) {
page.on('response', req => {
const url = req.url();
const status = req.status().toString();
let corrID = req.headers()['paypal-debug-id'];
if (corrID) {
corrID = corrID.split(',')[0];
}
if (status.startsWith('4') || status.startsWith('5')) {
log(status, url, corrID || '(unknown correlation id)');
}
});
}
export async function getElement(page : Object, selector : string) : Promise<Object> {
const element = await page.$(selector);
if (!element) {
throw new Error(`Could not find element: ${ selector }`);
}
return element;
}
export async function retry<T>(handler : () => Promise<T>, attempts : number) : Promise<T> {
try {
return await handler();
} catch (err) {
attempts -= 1;
if (!attempts) {
throw err;
}
log(`Failed with error, retrying (${ attempts } attempts remaining):`, err);
return retry(handler, attempts);
}
}
export async function withPage(handler : ({| page : Object |}) => Promise<void>) : Promise<void> {
const browser = await puppeteer.launch({
headless: HEADLESS,
devtools: DEVTOOLS,
ignoreHTTPSErrors: true,
args: [
'--no-sandbox'
]
});
try {
const page = await browser.newPage();
logFailedRequests(page);
await withMock(
methods.get(DOMAIN, {
status: 200,
body: '<head></head><body></body>'
}),
page,
async () => {
await retry(async () => {
await page.goto(DOMAIN);
await handler({ page });
}, RETRIES);
}
);
} catch (err) {
await browser.close();
throw err;
}
await browser.close();
}
export async function findFrameByName(page : Object, name : string) : Object {
log('FIND FRAME', name);
const namedFrame = (await page.frames()).find(frame => {
return frame.name().startsWith(name);
});
if (namedFrame) {
return namedFrame;
}
const element = await page.$(`iframe[name=${ name }]`);
try {
const frame = await element.contentFrame();
if (frame) {
log('FOUND FRAME', name);
await screenshot(page, `frame_opened`);
return page;
}
} catch (err) {
// pass
}
throw new Error(`Could not find frame with name: ${ name }`);
}
type PopupOpts = {| timeout? : number |};
const getDefaultPopupOpts = () : PopupOpts => {
// $FlowFixMe
return {};
};
export async function waitForPopup(page : Object, opts? : PopupOpts = getDefaultPopupOpts()) : Promise<Object> {
const { timeout = TIMEOUT * 1000 } = opts;
log('WAIT FOR POPUP');
const popupPage = await new Promise((resolve, reject) => {
const timer = setTimeout(() => {
reject(new Error(`Timed out waiting for popup window for ${ timeout }ms`));
}, timeout);
page.once('popup', (popup) => {
clearTimeout(timer);
log('POPUP OPENED');
resolve(popup);
});
});
logFailedRequests(popupPage);
await screenshot(popupPage, `popup_opened`);
return popupPage;
}
export async function delay(time : number) : Promise<void> {
return await new Promise((resolve) => {
setTimeout(resolve, time);
});
}
type ElementOpts = {| timeout? : number |};
const getDefaultElementOpts = () : ElementOpts => {
// $FlowFixMe
return {};
};
export async function waitForElement(page : Object, selector : string, opts? : ElementOpts = getDefaultElementOpts()) : Promise<void> {
const { timeout = TIMEOUT * 1000 } = opts;
log('WAIT FOR', selector);
await screenshot(page, `wait_for_${ selector }`);
try {
await page.waitForSelector(selector, { timeout });
} catch (err) {
await screenshot(page, `wait_for_${ selector }_failed`);
throw err;
}
await screenshot(page, `wait_for_${ selector }_success`);
}
type WaitOpts = {| timeout? : number |};
const getDefaultWaitOpts = () : WaitOpts => {
// $FlowFixMe
return {};
};
export async function waitAndType(page : Object, selector : string, text : string, opts? : WaitOpts = getDefaultWaitOpts()) : Promise<void> {
const { timeout = TIMEOUT * 1000 } = opts;
await waitForElement(page, selector, { timeout });
await delay(1000);
await screenshot(page, `pre_type_${ selector }`);
log('TYPE', selector, text);
await screenshot(page, `post_click_${ selector }`);
await page.type(selector, text);
}
export async function waitAndClick(page : Object, selector : string, opts? : WaitOpts = getDefaultWaitOpts()) : Promise<void> {
const { timeout = TIMEOUT * 1000 } = opts;
await waitForElement(page, selector, { timeout });
await delay(1000);
await screenshot(page, `pre_click_${ selector }`);
log('CLICK', selector);
await screenshot(page, `post_click_${ selector }`);
await page.click(selector);
}
export async function elementExists(page : Object, selector : string) : Promise<boolean> {
log('CHECK EXISTS', selector);
try {
await waitForElement(page, selector, { timeout: 1000 });
} catch (err) {
// pass
}
try {
if (await page.$(selector)) {
log('EXISTS', selector);
return true;
}
} catch (err) {
// pass
}
log('DOES NOT EXIST', selector);
return false;
}
export async function waitForClose(page : Object, opts? : WaitOpts = getDefaultWaitOpts()) : Promise<void> {
const { timeout = TIMEOUT * 1000 } = opts;
const start = Date.now();
log('WAIT FOR CLOSE');
await screenshot(page, `wait_close`);
return await new Promise((resolve, reject) => {
const interval = setInterval(async () => {
const elapsed = Date.now() - start;
if (await page.isClosed()) {
clearInterval(interval);
resolve();
}
if (elapsed > timeout) {
clearInterval(interval);
return reject(new Error(`Timed out after ${ timeout }ms waiting for page to close`));
}
}, 500);
});
}
export async function pause() : Promise<void> {
return await new Promise(() => {
// pass
});
}