-
Notifications
You must be signed in to change notification settings - Fork 791
/
puppeteer-page.ts
396 lines (334 loc) · 10.8 KB
/
puppeteer-page.ts
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
396
import type { E2EProcessEnv, EmulateConfig, HostElement, JestEnvironmentGlobal } from '@stencil/core/internal';
import type {
E2EPage,
E2EPageInternal,
FindSelector,
NewE2EPageOptions,
PageCloseOptions,
PageDiagnostic,
} from './puppeteer-declarations';
import type { ConsoleMessage, ConsoleMessageLocation, JSHandle, Page, WaitForOptions } from 'puppeteer';
import { find, findAll } from './puppeteer-element';
import { initPageEvents, waitForEvent } from './puppeteer-events';
import { initPageScreenshot } from './puppeteer-screenshot';
declare const global: JestEnvironmentGlobal;
const env: E2EProcessEnv = process.env;
export async function newE2EPage(opts: NewE2EPageOptions = {}): Promise<E2EPage> {
if (!global.__NEW_TEST_PAGE__) {
throw new Error(`newE2EPage() is only available from E2E tests, and ran with the --e2e cmd line flag.`);
}
const page: E2EPageInternal = await global.__NEW_TEST_PAGE__();
const diagnostics: PageDiagnostic[] = [];
try {
page._e2eElements = [];
page._e2eGoto = page.goto;
page._e2eClose = page.close;
await setPageEmulate(page as any);
await page.setCacheEnabled(false);
await initPageEvents(page);
initPageScreenshot(page);
let docPromise: Promise<JSHandle> = null;
page.close = async (options?: PageCloseOptions) => {
try {
if (Array.isArray(page._e2eElements)) {
const disposes = page._e2eElements.map(async (elmHande) => {
if (typeof elmHande.e2eDispose === 'function') {
await elmHande.e2eDispose();
}
});
await Promise.all(disposes);
}
} catch (e) {}
const noop: any = () => {
throw new Error('The page was already closed');
};
page._e2eElements = noop;
page._e2eEvents = noop;
page._e2eGoto = noop;
page.find = noop;
page.debugger = noop;
page.findAll = noop;
page.compareScreenshot = noop;
page.setContent = noop;
page.spyOnEvent = noop;
page.waitForChanges = noop;
page.waitForEvent = noop;
try {
if (!page.isClosed()) {
await page._e2eClose(options);
}
} catch (e) {}
};
const getDocHandle = async () => {
if (!docPromise) {
docPromise = page.evaluateHandle(() => document);
}
const documentJsHandle = await docPromise;
return documentJsHandle.asElement();
};
page.find = async (selector: FindSelector) => {
const docHandle = await getDocHandle();
return find(page, docHandle, selector) as any;
};
page.findAll = async (selector: FindSelector) => {
const docHandle = await getDocHandle();
return findAll(page, docHandle, selector) as any;
};
page.waitForEvent = async (eventName) => {
const docHandle = await getDocHandle();
return waitForEvent(page, eventName, docHandle);
};
page.getDiagnostics = () => {
return diagnostics;
};
page.waitForChanges = waitForChanges.bind(null, page);
page.debugger = () => {
if (env.__STENCIL_E2E_DEVTOOLS__ !== 'true') {
throw new Error('Set the --devtools flag in order to use E2EPage.debugger()');
}
return page.evaluate(() => {
return new Promise<void>((resolve) => {
// tslint:disable-next-line: no-debugger
debugger;
resolve();
});
}) as any;
};
const failOnConsoleError = opts.failOnConsoleError === true;
const failOnNetworkError = opts.failOnNetworkError === true;
page.on('console', (ev) => {
if (ev.type() === 'error') {
diagnostics.push({
type: 'error',
message: ev.text(),
location: ev.location().url,
});
if (failOnConsoleError) {
fail(new Error(serializeConsoleMessage(ev)));
}
}
consoleMessage(ev);
});
page.on('pageerror', (err: Error) => {
diagnostics.push({
type: 'pageerror',
message: err.message,
location: err.stack,
});
fail(err);
});
page.on('requestfailed', (req) => {
diagnostics.push({
type: 'requestfailed',
message: req.failure().errorText,
location: req.url(),
});
if (failOnNetworkError) {
fail(new Error(req.failure().errorText));
} else {
console.error('requestfailed', req.url());
}
});
if (typeof opts.html === 'string') {
await e2eSetContent(page, opts.html, { waitUntil: opts.waitUntil });
} else if (typeof opts.url === 'string') {
await e2eGoTo(page, opts.url, { waitUntil: opts.waitUntil });
} else {
page.goto = e2eGoTo.bind(null, page);
page.setContent = e2eSetContent.bind(null, page);
}
} catch (e) {
if (page) {
if (!page.isClosed()) {
await page.close();
}
}
throw e;
}
return page;
}
async function e2eGoTo(page: E2EPageInternal, url: string, options: WaitForOptions = {}) {
if (page.isClosed()) {
throw new Error('e2eGoTo unavailable: page already closed');
}
if (typeof url !== 'string') {
throw new Error('invalid gotoTest() url');
}
if (!url.startsWith('/')) {
throw new Error('gotoTest() url must start with /');
}
const browserUrl = env.__STENCIL_BROWSER_URL__;
if (typeof browserUrl !== 'string') {
throw new Error('invalid gotoTest() browser url');
}
const fullUrl = browserUrl + url.substring(1);
if (!options.waitUntil) {
options.waitUntil = env.__STENCIL_BROWSER_WAIT_UNTIL as any;
}
const rsp = await page._e2eGoto(fullUrl, options);
if (!rsp.ok()) {
throw new Error(`Testing unable to load ${url}, HTTP status: ${rsp.status()}`);
}
await waitForStencil(page, options);
return rsp;
}
async function e2eSetContent(page: E2EPageInternal, html: string, options: WaitForOptions = {}) {
if (page.isClosed()) {
throw new Error('e2eSetContent unavailable: page already closed');
}
if (typeof html !== 'string') {
throw new Error('invalid e2eSetContent() html');
}
const output: string[] = [];
const appScriptUrl = env.__STENCIL_APP_SCRIPT_URL__;
if (typeof appScriptUrl !== 'string') {
throw new Error('invalid e2eSetContent() app script url');
}
output.push(`<!doctype html>`);
output.push(`<html>`);
output.push(`<head>`);
const appStyleUrl = env.__STENCIL_APP_STYLE_URL__;
if (typeof appStyleUrl === 'string') {
output.push(`<link rel="stylesheet" href="${appStyleUrl}">`);
}
output.push(`<script type="module" src="${appScriptUrl}"></script>`);
output.push(`</head>`);
output.push(`<body>`);
output.push(html);
output.push(`</body>`);
output.push(`</html>`);
const pageUrl = env.__STENCIL_BROWSER_URL__;
await page.setRequestInterception(true);
const interceptedReqCallback = (interceptedRequest: any) => {
if (pageUrl === interceptedRequest.url()) {
interceptedRequest.respond({
status: 200,
contentType: 'text/html',
body: output.join('\n'),
});
} else {
interceptedRequest.continue();
}
};
page.on('request', interceptedReqCallback);
if (!options.waitUntil) {
options.waitUntil = env.__STENCIL_BROWSER_WAIT_UNTIL as any;
}
const rsp = await page._e2eGoto(pageUrl, options);
if (!rsp.ok()) {
throw new Error(`Testing unable to load content`);
}
await waitForStencil(page, options);
return rsp;
}
async function waitForStencil(page: E2EPage, options: WaitForOptions) {
try {
const timeout = typeof options.timeout === 'number' ? options.timeout : 4750;
await page.waitForFunction('window.stencilAppLoaded', { timeout });
} catch (e) {
throw new Error(`App did not load in allowed time. Please ensure the content loads a stencil application.`);
}
}
async function setPageEmulate(page: Page) {
if (page.isClosed()) {
return;
}
const emulateJsonContent = env.__STENCIL_EMULATE__;
if (!emulateJsonContent) {
return;
}
const screenshotEmulate = JSON.parse(emulateJsonContent) as EmulateConfig;
const emulateOptions = {
viewport: screenshotEmulate.viewport,
userAgent: screenshotEmulate.userAgent,
};
await (page as Page).emulate(emulateOptions);
}
async function waitForChanges(page: E2EPageInternal) {
try {
if (page.isClosed()) {
return;
}
await Promise.all(page._e2eElements.map((elm) => elm.e2eRunActions()));
if (page.isClosed()) {
return;
}
await page.evaluate(() => {
// BROWSER CONTEXT
return new Promise<void>((resolve) => {
requestAnimationFrame(() => {
const promises: Promise<any>[] = [];
const waitComponentOnReady = (elm: Element | ShadowRoot, promises: Promise<any>[]) => {
if (elm != null) {
if ('shadowRoot' in elm && elm.shadowRoot instanceof ShadowRoot) {
waitComponentOnReady(elm.shadowRoot, promises);
}
const children = elm.children;
const len = children.length;
for (let i = 0; i < len; i++) {
const childElm = children[i];
if (childElm != null) {
if (
childElm.tagName.includes('-') &&
typeof (childElm as HostElement).componentOnReady === 'function'
) {
promises.push((childElm as HostElement).componentOnReady());
}
waitComponentOnReady(childElm, promises);
}
}
}
};
waitComponentOnReady(document.documentElement, promises);
Promise.all(promises)
.then(() => {
resolve();
})
.catch(() => {
resolve();
});
});
});
});
if (page.isClosed()) {
return;
}
if (typeof (page as any).waitForTimeout === 'function') {
// https://github.com/puppeteer/puppeteer/issues/6214
await (page as any).waitForTimeout(100);
} else {
await page.waitFor(100);
}
await Promise.all(page._e2eElements.map((elm) => elm.e2eSync()));
} catch (e) {}
}
function consoleMessage(c: ConsoleMessage) {
const msg = serializeConsoleMessage(c);
const type = c.type();
const normalizedType = type === 'warning' ? 'warn' : type;
if (normalizedType === 'debug') {
// Skip debug messages
return;
}
if (typeof (console as any)[normalizedType] === 'function') {
(console as any)[normalizedType](msg);
} else {
console.log(type, msg);
}
}
function serializeConsoleMessage(c: ConsoleMessage) {
return `${c.text()} ${serializeLocation(c.location())}`;
}
function serializeLocation(loc: ConsoleMessageLocation) {
let locStr = '';
if (loc && loc.url) {
locStr = `\nLocation: ${loc.url}`;
if (loc.lineNumber) {
locStr += `:${loc.lineNumber}`;
}
if (loc.columnNumber) {
locStr += `:${loc.columnNumber}`;
}
}
return locStr;
}